了解结构的 Swift 属性和赋值中的 类 的区别
Understanding difference in Swift properties for structs and classes in assignment
我的问题是关于我在编写函数以初始化结构中的可选数组时不断看到的错误,我通过将结构更改为 class 解决了这个问题。我希望有人可以向我解释我对导致此问题的结构和 classes 不了解的地方。这是我的代码。
struct DataStorage {
//When I change this to class DataStorage this works
var listOfVariables = [VariableType]
var allDataPoints: [[DataPoint]]?
init() {
listOfVariables = VariableType.getAllVariables(managedObjectContext)
}
func initializeAllDataPoints() {
//THIS IS THE LINE IN QUESTION
allDataPoints = [[DataPoint]](count: listOfVariables.count, repeatedValue: [DataPoint]())
}
}
所以,函数 initializeAllDataPoints
是导致错误的原因,这确实是这个问题的相关部分。我得到的错误是 Cannot assign to 'allDataPoints' in 'self'
。我只在 DataStorage
是一个结构时得到这个错误,而当 DataStorage
是一个 class 时我没有得到它。关于导致这种行为差异的 classes 和结构,我有什么不理解的?
每当 struct
中的方法修改其自身的属性之一时,您必须使用 mutating
关键字。
我相信如果你写:
mutating func intializeAllDataPoints() { ... }
它应该适合你。
This article 提供了更多背景信息。
我的问题是关于我在编写函数以初始化结构中的可选数组时不断看到的错误,我通过将结构更改为 class 解决了这个问题。我希望有人可以向我解释我对导致此问题的结构和 classes 不了解的地方。这是我的代码。
struct DataStorage {
//When I change this to class DataStorage this works
var listOfVariables = [VariableType]
var allDataPoints: [[DataPoint]]?
init() {
listOfVariables = VariableType.getAllVariables(managedObjectContext)
}
func initializeAllDataPoints() {
//THIS IS THE LINE IN QUESTION
allDataPoints = [[DataPoint]](count: listOfVariables.count, repeatedValue: [DataPoint]())
}
}
所以,函数 initializeAllDataPoints
是导致错误的原因,这确实是这个问题的相关部分。我得到的错误是 Cannot assign to 'allDataPoints' in 'self'
。我只在 DataStorage
是一个结构时得到这个错误,而当 DataStorage
是一个 class 时我没有得到它。关于导致这种行为差异的 classes 和结构,我有什么不理解的?
每当 struct
中的方法修改其自身的属性之一时,您必须使用 mutating
关键字。
我相信如果你写:
mutating func intializeAllDataPoints() { ... }
它应该适合你。
This article 提供了更多背景信息。