gpt4 book ai didi

ios - 为什么在 Swift 中初始化变量时会出现 "Variable used before being initialized"错误?

转载 作者:行者123 更新时间:2023-11-30 13:23:04 24 4
gpt4 key购买 nike

我很难理解为什么我在使用 Swift 的 iOS 项目中遇到这个编译器错误。如果我创建以下类:

class InitTest {

let a: Int
let b: Int
let c: Int

init () {
self.a = 3
self.b = 4
self.c = self.runCalculation()
}

func runCalculation () -> Int {
return self.a * self.b
}
}

我在 self.c = self.runCalculation() 行上收到编译器错误,提示“变量‘self.c’在初始化之前使用”。

起初我以为这是因为编译器无法验证 runCalculation() 方法没有访问 self.c,但后来我尝试混合 init 方法向上一点:

init () {
self.a = 3
self.c = self.runCalculation()
self.b = 4
}

这次错误是“变量'self.b'在初始化之前使用”(在同一self.runCalculation()行上)。这表明编译器能够检查该方法访问哪些属性,因此据我所知,初始情况应该没有问题。

当然,这是一个简单的示例,我可以轻松重构以避免调用计算方法,但在实际项目中可能会有多个计算,每个计算都可能非常复杂。我希望能够分离出逻辑以保持可读性。

幸运的是,有一个简单的解决方法:

init () {
self.a = 3
self.b = 4

self.c = 0
self.c = self.runCalculation()
}

(或使用属性初始化器 let c = 0),但我想了解为什么编译器对第一个示例有问题。我是否遗漏了什么或者这是不必要的限制?

最佳答案

Swift 之所以出现这种行为,是因为两阶段初始化。来自 Apple 的 Swift 书籍:

Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.

在第一阶段结束之前,类需要某种默认值。自定义值是第二阶段的一部分。

Objective-C 没有这种行为,因为它总是可以为基元提供 0 作为默认值,为对象提供 nil,但在 Swift 中没有机制可以提供这样的默认值。

关于ios - 为什么在 Swift 中初始化变量时会出现 "Variable used before being initialized"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37552156/

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