![](/img/trans.png)
[英]Why is 'didset' called on a property when I set the property of that property?
[英]Swift property only being set correctly when a didSet is present (can be empty)
我有一個類Tweet
,它有一個名為id
的UInt
屬性,當它在初始化程序中設置時,如果存在didSet
方法,它只會被設置為我設置的值。 更令人困惑的是didSet
可以為空,但它仍然有效。
這是該類的簡化版本:
class Tweet: ObservableObject, Identifiable {
@Published var id: UInt = 0 {
didSet {
}
}
init() {
}
init(id: UInt) {
self.id = id
}
convenience init(from json: JSON) {
self.init()
if let id = json["id_str"].string {
self.id = UInt(id) ?? 0
}
}
}
例如,在便利 init 中, UInt(id)
可以是1197998964525731840
。 如果didSet
存在,如上所述,稍后在 SwiftUI 視圖中使用時,該值將為1197998964525731840
。 如果didSet
不存在,則值將始終為10749289280
,無論原始值是什么,直到您重新啟動應用程序。
該項目可以在這里找到,據我所知,與此問題相關的文件是Tweet.swift和TweetView.swift 。 注釋/取消注釋第 15-19 行,然后運行應用程序,在文本字段中輸入搜索詞,按 go 並向下滾動以點擊每條推文右下角的鏈接按鈕(URL 和id
打印在控制台)。
我使用id
來存儲個人推文 ID 和可識別協議的事實似乎是導致錯誤的原因。
var id = UUID()
@Published var identifier: UInt = 0
上述更改修復了它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.