简体   繁体   English

如何访问类常量和变量

[英]How to access class constants and variables

Why can I not perform operations with a variable or constant at the class level? 为什么我不能在类级别使用变量或常量执行操作? Is this not allowed or is there a keyword I need to use to access them? 这是不允许的还是我需要用来访问它们的关键字? Is this bad practice? 这是不好的做法吗?

Controller: 控制器:

class ViewController: UIViewController {
    let one = 1
    let two = 2
    var sum = one + two
}

Error: 错误:

ViewController.Type does not have a member named 'one'

Class variables and constants must be static , eg, static let one = 1 . 类变量和常量必须是static ,例如, static let one = 1

Here it suffices for the two let constants to be static for them to be usable in initializing both class and instance variables. 这里两个let常量是static ,它们可用于初始化类和实例变量。 The following works for me: 以下适用于我:

class MyClass {
    static let one = 1
    static let two = 2
    static var sum = one + two
    var instanceProduct = one * two
}

MyClass.one
MyClass.sum
MyClass().instanceProduct

Note that in the above example you can do MyClass.sum = 5 . 请注意,在上面的示例中,您可以执行MyClass.sum = 5 If you meant the sum to be constant as well, simply change it to static let sum = one + two . 如果你的意思是总和也是常数,只需将其改为static let sum = one + two

The requirement is that the constants you use outside of any functions and closures be declared static let . 要求是在任何函数和闭包之外使用的常量声明为static let The implication of this is that they are truly constant for the entire class. 这意味着它们对整个班级来说都是不变的。 If you need instance-specific constants, you cannot use them outside of functions or closures (as you've noticed) – as a workaround for a variable sum I would suggest a lazy variable initialized by a closure: 如果你需要特定于实例的常量,你不能在函数或闭包之外使用它们(正如你所注意到的) - 作为变量sum的变通方法我会建议一个由闭包初始化的lazy变量:

class MyClass {
    let one: Int // value given in `init`
    let two = 2
    lazy var sum: Int = { self.one + self.two }()

    init(one: Int = 1) {
        self.one = one
    }
}
MyClass().sum // 3
MyClass(one: 2).sum // 4

Simple fix 简单的修复

   override func viewDidLoad() {
        super.viewDidLoad()
        var result = one + two
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM