简体   繁体   English

Swift中存储的属性不能互相引用吗?

[英]Stored properties in Swift can't refer to each other?

What is the reason I can't give a value to a stored property that depends on the value of another one in Swift 2.0? 为什么我不能给依赖于Swift 2.0中另一个stored property值的stored property值的原因是什么?

The code below gives an error saying: 下面的代码给出了一个错误信息:

Something.Type does not have a member named 'foo' Something.Type没有名为'foo'的成员

class Something {
    let foo = "bar"
    let baz = "\(foo) baz"
}

This is odd, as Something.Type certainly does have a member called foo. 这很奇怪,因为Something.Type确实有一个名为foo的成员。

Is there a way around this? 有没有解决的办法?

Looks like you're trying to initialise the variable baz , before swift has had a chance to know that foo is a property of Something . 看来您正在尝试初始化变量baz ,而swift才有机会知道fooSomething的属性。 Place your initialisation inside the init constructor. 将您的初始化放入init构造函数中。

class Something {
    let foo: String
    let baz: String

    init () {
        foo = "bar"
        baz = "\(foo) baz"
    }
}

You can also use lazy initialization but now you have to make it a variable: 您还可以使用lazy初始化,但现在必须将其设置为变量:

class Something {
    let foo = "bar"
    lazy var baz = { "\(self.foo) baz" }()
}

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

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