简体   繁体   中英

Swift: Recursively setting computed property

In Swift 3, I am declaring a computed property that will always return a non-nil positive value. The property is stored in UserDefaults (which means that it will be nil the first time the app runs):

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")
    }
}

On line 6 and 7:

notificationInterval = defaultInterval
return notificationInterval

I get the following error:

Attempting to access 'notificationInterval' within its own getter.

I understand the error, but how would I design this differently? I am accessing the property "within its own getter" on purpose.

do the check for correct data in the setter, something like

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")
        }
    }
}

To fix the warning, just replace

notificationInterval = defaultInterval
return notificationInterval

with

return defaultInterval

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

You can use the register function to register your default value so that it is available from UserDefaults the first time the program is run.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM