In this answer,建议使用lazy
标记属性,以便根据其他属性定义属性。这似乎很干净,比其他SO答案的建议更可取。
但是,遵循此建议仍会生成错误消息:Instance member cannot be used on type error
定义tutorial
的正确方法是什么,以便在使用lazy
时可以包含其他属性?
class TestViewController: UIViewController {
let Key1 = "Key1"
let Key2 = "Key2"
lazy var tutorial = [Key1, Key2]
}
创建了这个简单的类来测试@ dfri的建议,但错误仍然存在:
import Foundation
class Test {
let Foo = "foo"
lazy var bar = Foo
}
答案 0 :(得分:3)
我可能会误解你,但你是否正在寻找以下内容?
class Foo {
let Key1 = "Key1"
let Key2 = "Key2"
lazy var tutorial : [String] = { [self.Key1, self.Key2] }()
/* Alternatively:
lazy var tutorial : [String] = [self.Key1, self.Key2] */
init() {}
}
请注意,我使用前缀.self
访问同一类属性。
或者,只使用计算属性。在上面的简单示例中,Key1
和Key2
是不可变的,因此没有理由让教程成为一个懒惰的存储的属性:
class Foo {
let Key1 = "Key1"
let Key2 = "Key2"
/* now as a computed property: */
var tutorial : [String] { return [Key1, Key2] }
init() {}
}
如果Key1
和Key2
是可变的,那么上面的两个解决方案会有所不同:
lazy var tutorial
会在{em>当前值为Key1
和Key2
当时进行懒惰初始化(首次使用时),但不受后来Key1
和/或Key2
中的更改的影响。tutorial
成为计算属性,但总会产生(计算的)数组Key1
和/或Key2
的当前值。编辑添加(编辑后的问题):
对于您问题中的更新示例,lazy变量的使用方式与上述相同:
class TestViewController: UIViewController {
let Key1 = "Key1"
let Key2 = "Key2"
lazy var tutorial : [String] = [self.Key1, self.Key2]
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}