gpt4 book ai didi

swift - 隐式解包 当初始化期间无法定义常量但出现错误时可选

转载 作者:行者123 更新时间:2023-11-30 10:01:15 26 4
gpt4 key购买 nike

作者:Drewag 在对 the question 的回答中

Every member constant must have a value by the time initialization is complete. Sometimes, a constant cannot be initialized with its correct value during initialization, but it can still be guaranteed to have a value before being accessed.

Using an Optional variable gets around this issue because an Optional is automatically initialized with nil and the value it will eventually contain will still be immutable. However, it can be a pain to be constantly unwrapping a variable that you know for sure is not nil. Implicitly Unwrapped Optionals achieve the same benefits as an Optional with the added benefit that one does not have to explicitly unwrap it everywhere.

以下代码定义了两个类,CountryCity,每个类都将另一个类的实例存储为属性。每个国家都必须有一个首都,而每个城市都必须属于一个国家。

class Country {
let name: String
var capitalCity: City! //why I can't use let!
init(name: String, capitalName: String){
self.name = name
self.capitalCity = City(name: capitalName, country: self)
}

deinit {
print("\(name) has been de-initialized the city \(capitalCity.name) is gone with with the country")
}

}

class City{
let name: String
unowned let country: Country
init(name: String, country: Country){
self.name = name
self.country = country
}

deinit {
print("The city \(name) has been de-initialized ")
}
}

var country = Country(name: "Canada", capitalName: "Ottawa")
}

但是,如果我将 var CapitalCity: City! 行更改为 let CapitalCity: City!,编译器会发出以下错误警告。

enter image description here

问题:当初始化期间无法定义常量时,我​​们是否可以使用隐式解包可选?这里有什么错误?

最佳答案

重要的部分在这里:

City(name: capitalName, country: self)

您肯定在表达式中使用了 self,该表达式在分配给属性 capitalCity 之前执行。

如果你想在任何表达式中使用self,它需要在 two phase initialization 的第二阶段,这意味着在使用 self 之前需要初始化所有属性。

通过使用 var,Swift 为属性 capitalCity 分配默认初始值 nil。因此该属性可以被视为“已初始化”,因此,您可以在初始化另一个属性 name 后使用 self

(您知道将 nil 赋予 ImplicitlyUnwrappedOptional 的 let 常量是荒谬的。)

顺便说一句,private(set) var经常用于类似的情况:

    private(set) var capitalCity: City!

关于swift - 隐式解包 当初始化期间无法定义常量但出现错误时可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38410359/

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