我是 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/