gpt4 book ai didi

swift - 它如何在没有实例的情况下快速执行类?

转载 作者:行者123 更新时间:2023-11-28 11:13:52 25 4
gpt4 key购买 nike

我是 swift 的新手,有一些我无法理解的东西,它是关于类执行的。我认为类不能自己执行它们,你需要定义一个实例变量来使用类的方法和属性,但我在 xcode 文件中注意到类没有实例变量,这是为什么?以及类如何在没有实例的情况下自行执行?

提前致谢

    import UIKit

class ViewController: UIViewController {
var theView: UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.redColor()

}

}
/// Why i donl't need this line of code to worke with the class above
/// instead the class above execute itself without this instance
var theViewControllerInstance = ViewController()

最佳答案

通常你会创建一个类的实例来执行一个函数,但如果你愿意的话;你可以创建一个类函数:

class MyClass {
class func myClassMethod() {
print("This is printed from a class function")
}

func myInstanceMethod() {
print("This is printed from a normal function")
}
}

按以下方式使用类函数:

MyClass.myClassMethod()

像这样的标准函数:

let myInstance = MyClass()
myInstance.myInstanceMethod()

关于swift - 它如何在没有实例的情况下快速执行类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33113570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com