sunshinejr / SwiftyUserDefaults

Modern Swift API for NSUserDefaults
http://radex.io/swift/nsuserdefaults/static
MIT License
4.86k stars 367 forks source link

[Crash] Use `DefaultsKeys` to handle `AppleLanguages` cause crash of WebKit #303

Open K6F opened 3 months ago

K6F commented 3 months ago

Hi, Thank you for your great job of SwiftyUserDefaults, it an excellent library and helps a lot.

Currently we got an issue:

We have a code like

extension DefaultsKeys {   
    var appleLanguages: DefaultsKey<[String]> { .init("AppleLanguages", defaultValue: ["en"]) }   
}   

to manage AppleLanguages of App, But as the AppleLanguages contains a value [String] which is Encodable, when we set a new value to it, it will trigger the code:

    /// Encodes passed `encodable` and saves the resulting data into the user defaults for the key `key`.   
    /// Any error encoding will result in an assertion failure.   
    func set<T: Encodable>(encodable: T, forKey key: String) {   
        do {   
            let data = try JSONEncoder().encode(encodable)   
            set(data, forKey: key)    
        } catch {   
            assertionFailure("Failure encoding encodable of type \(T.self): \(error.localizedDescription)")   
        }   
    }   

and the value is encoded to Data and set in Defaults.

Then, if you open a web view, it will cause a crash because WebKit read UserDefaults.standard.array(forKey: "AppleLanguages") but returns nil.

Any suggestion about how we can manage AppleLanguages with DefaultsKeys correctly? Or we can only fall back to use UserDefaults?