我正在关注SwiftUI 的 100 天,并已达到第 37 天。在使用 UserDefaults 进行永久更改时,我遇到了didSet
.
(我在 iOS 13.4 中使用 Swift 5)
在示例代码中,它写道
.navigationBarItems(trailing: Button("Save") {
if let actualAmount = Int(self.amount) {
let item = ExpenseItem(name: self.name, type: self.type, amount: actualAmount)
self.expenses.items.append(item)
}
})
didSet
应该在哪里调用.append()
。
但是,在实践中,didSet
除非我将上面的代码更改为
.navigationBarItems(trailing: Button("Save") {
if let actualAmount = Int(self.amount) {
let item = ExpenseItem(name: self.name, type: self.type, amount: actualAmount)
let newItems = self.expenses.items + [item]
self.expenses.items = newItems
}
})
我还在 Playground 中编写了一个小测试(见下文),这表明它.append()
与didSet
struct Count {
var array: [Int] {
didSet {
print("struct Count - didSet() called")
}
}
}
class CountClass {
var array: [Int] {
didSet {
print("class CountClass - didSet() called")
}
}
init() {
array = [1, 2, 3]
}
}
struct Test {
var countA = Count(array: [1, 2, 3])
var countB = CountClass()
mutating func testDidSet() {
countA.array.append(4)
countB.array.append(4)
}
}
var t = Test()
t.testDidSet()
这种奇怪的行为真的让我想知道它是如何didSet
工作的。还是这个问题与使用有关@ObservedObject
(示例项目就是这种情况)?
PS:我从Project7下载了汉化版,也有这个问题。