2017-01-19 55 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