2017-01-19 90 views
0

在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. 

我明白這個錯誤,但我會如何設計這個不同呢?我正在有目的地訪問該屬性「在其自己的獲取者內」。

+0

避免顯式檢查'nil'然後強制解包。只需使用條件綁定。 – Alexander

回答

0

做在二傳手正確的數據校驗,像

var notificationInterval: TimeInterval { 
    get { 
     if let interval = UserDefaults(suiteName: "groupName")?.double(forKey: "notificationInterval") as? TimeInterval { 
       return interval 
     } else { 
      return defaultInterval 
     } 
    } 

    set { 
     if let interval = newValue, interval <= 0 { 
      UserDefaults(suiteName: "groupName")?.set(defaultInterval , forKey: "notificationInterval") 
     } else { 
      UserDefaults(suiteName: "groupName")?.set(newValue, forKey: "notificationInterval") 
     } 
    } 
} 
0

要解決的警告,只需更換

notificationInterval = defaultInterval 
return notificationInterval 

return defaultInterval 

... which means that it will be nil the first time the app runs

你可以使用register函數收集您的默認值,以便在程序第一次運行時從UserDefaults獲得。

let dict: [String: Any] = ["notificationInterval": 5.0] 
UserDefaults.standard.register(defaults: dict) 

let interval = UserDefaults.standard.double(forKey: "notificationInterval") 
// interval = 5