Search code examples
iosswiftnsuserdefaults

Conditional cast from string to string always succeds in swift 3


enter image description here

func resetUserDefaults() {
    let userDefaults = UserDefaults.standard
    let dict = userDefaults.dictionaryRepresentation()

    for (key,_) in dict {
        if let key = key as? String {
            userDefaults.removeObject(forKey: key)
        } else {
            #if DEBUG
                NSLog("\(key)")
            #endif
        }
    }
}

I'm getting this warning. can anyone suggest me how to avoid this warnoing


Solution

  • All keys in UserDefaults must be of type String. So key is declared as a String. So attempting to cast it to a String is pointless. Hence the warning.

    All you need is:

    func resetUserDefaults() {
        let userDefaults = UserDefaults.standard
        let dict = userDefaults.dictionaryRepresentation()
    
        for (key,_) in dict {
            userDefaults.removeObject(forKey: key)
        }
    }