在Swift 3中,我聲明瞭一個總是返回非零正值的計算屬性。的屬性被存儲在UserDefaults(這意味着,這將是零首次應用運行):Swift:遞歸設置計算屬性
var notificationInterval: TimeInterval {
get {
let interval = UserDefaults(suiteName: "groupName")?.double(forKey: "notificationInterval") as TimeInterval?
if interval == nil || interval! <= 0 {
notificationInterval = defaultInterval
return notificationInterval
} else {
return interval!
}
}
set {
UserDefaults(suiteName: "groupName")?.set(newValue, forKey: "notificationInterval")
}
}
在管線6和7:
notificationInterval = defaultInterval
return notificationInterval
我得到以下錯誤:
Attempting to access 'notificationInterval' within its own getter.
我明白這個錯誤,但我會如何設計這個不同呢?我正在有目的地訪問該屬性「在其自己的獲取者內」。
避免顯式檢查'nil'然後強制解包。只需使用條件綁定。 – Alexander