简体   繁体   中英

Is there a way to declare a constant inside a computed property in Swift 3?

I have several properties like this in my Swift 3 code:

var dinActive: Bool {
    get { return UserDefaults.standard.bool (forKey: "bo", fallback: true) }
    set { UserDefaults.standard.set (newValue, forKey: "bo") }
}
var spdif1Active: Bool {
    get { return UserDefaults.standard.bool (forKey: "spdif1", fallback: true) }
    set { UserDefaults.standard.set (newValue, forKey: "spdif1") }
}

I wonder if I can make this more compact. Eg, I'd avoid repeating the string literal in both getter and setter functions, like with let s = "bo" . Is that possible in some way?

Also, I wonder if I can make this repeated pattern into even shorter code, like I could do with classes and generics, or with a #define macro in C. Though, that's probably better asked in a separate question. If you have a suggestion for that and it's not answered on SO yet, just add a comment and I'll make a new question of it.

you can create a let constant outside of your class for it. For example:

//declaring constant outside of class
let SPDif1Key: String = "spdif1"

class YourClass
{
    var dinActive: Bool {
        get { return UserDefaults.standard.bool (forKey: SPDif1Key, fallback: true) }
        set { UserDefaults.standard.set (newValue, forKey: SPDif1Key) }
    }
}

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