gpt4 book ai didi

initialization - Swift 类属性 - 这需要初始化吗?

转载 作者:行者123 更新时间:2023-11-28 07:17:55 25 4
gpt4 key购买 nike

class Something {
...
}

class AnotherThing {

let foo: Something

init(something: Something) {
foo = something
}
}

class ReallyGreatClass {

let aSomething = Something();
let anotherThing = AnotherThing(something: aSomething);

}

ReallyGreatClass 抛出以下编译器错误:

ReallyGreatClass.Type does not have a member named 'aSomething'

The Swift Programming Language 的 Initialization 一章的副标题下 Setting a Default Property Value with a Closure or Function 他们抛弃了初始化属性默认值的概念关闭;所以让我们试一试:

let anotherThing: AnotherThing = {
return AnotherThing(something: aSomething)
}()

嗯,当然,这行不通 - 它不应该。如本章所述:

If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values. You also cannot use the implicit self property, or call any of the instance’s methods.

所以,我发现解决这个问题的唯一方法是包含一个初始化方法:

init() {
anotherThing = AnotherThing(something: aSomething)
}

但是,我需要一个单行初始化方法来设置 anotherThing 属性,这似乎很奇怪。我想知道我是否遗漏了什么并且有一种方法可以设置属性的默认值而不需要初始化程序。

最佳答案

你没有错过任何东西。如果要在初始化中使用另一个属性,则必须使用初始化方法。

关于initialization - Swift 类属性 - 这需要初始化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com