mardi 11 août 2015

How do I beautify a cache "pattern" in Swift?

I have a settings service in my Swift project which defines variables for all settings that are available in my app. In order to access the NSUserDefaults only when absolutely necessary (in order to avoid non-essential delays), I use cache variables for these settings:

class SettingsService {

    struct UserDefaults {
        static let Setting1 = "Setting1"
    }

    private var setting1Cache : Bool?
    var setting1 : Bool {
        get {
            if let value = setting1Cache {
                return value
            }
            let value = NSUserDefaults.standardUserDefaults().boolForKey(UserDefaults.Setting1)
            setting1Cache = value
            return value
        }
        set {
            setting1Cache = newValue
            NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: UserDefaults.Setting1)
        }
    }
}

Although the code should work, the class will soon become really bloated when the number of available settings increases. Is there any way to make the code significantly more concise besides defining a helper function for the first 4 lines of the getter?

Aucun commentaire:

Enregistrer un commentaire