onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to use subscript in Swift #861

Open onmyway133 opened 2 years ago

onmyway133 commented 2 years ago

Make it easy to access common cases, for example UserDefaults

extension UserDefaults {
    enum Key: String {
        case hasBackup
    }

    subscript(key: Key) -> Bool {
        get {
            bool(forKey: key.rawValue)
        }
        set {
            set(newValue, forKey: key.rawValue)
        }
    }
}

UserDefaults.standard.hasBackup] = true
oe commented 2 years ago

the last line should be UserDefaults.standard[.hasBackup] = true