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

How it can execute classes in swift without instance?

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

提前致谢

    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 的实例来执行一个函数,但如果你愿意的话;你可以做一个class函数:

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

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

您按以下方式使用 class 函数:

MyClass.myClassMethod()

像这样的标准函数:

let myInstance = MyClass()
myInstance.myInstanceMethod()

您可以创建一个 ViewController 实例并自己完成所有工作,但更常见的方法是在应用程序启动时在界面构建器(故事板或 xib)中绑定此 class并加载 UI 资源,实例已为您创建。