blog icon indicating copy to clipboard operation
blog copied to clipboard

How to use subscript in Swift

Open onmyway133 opened this issue 3 years ago • 1 comments

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

onmyway133 avatar Feb 05 '22 06:02 onmyway133

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

oe avatar Apr 21 '22 15:04 oe