sunshinejr / SwiftyUserDefaults

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

Add Codable support from Swift 4 to simplify storing complex objects #146

Closed Jeehut closed 6 years ago

Jeehut commented 6 years ago

With Swift 4 we have a new and shiny feature that would make saving complex objects into the User Defaults really simple. I know, the UserDefaults are not meant to be used for complex objects (that's what databases are for) but still sometimes there's a not too complex object (like the user settings) which might be more practical if it was saved as one object under one key instead of generating keys for any possible setting option.

For Storing the object it could be converted to JSON and saved as a plain String. I'd love to see this, there's even another library that already implements this, but I like the approach of SwiftyUserDefaults better (there you have to explicitly specify the type of the object for example): https://github.com/Nirma/Default

jgrund01 commented 6 years ago

Big +1 on this. This would be super helpful being able to store existing types we have that conform to Codable.

calismatest commented 6 years ago
struct Test: Codable {
    public var workId: Int?
}
extension DefaultsKeys {
    static let test = DefaultsKey<Test?>("test")
}
extension UserDefaults {
    subscript<T: Codable>(key: DefaultsKey<T?>) -> T? {
        get {
            guard let data = object(forKey: key._key) as? Data else { return nil }

            let decoder = JSONDecoder()
            let dictionary = try! decoder.decode([String: T].self, from: data)
            return dictionary["top"]
        }
        set {
            guard let value = newValue else { return set(nil, forKey: key._key) }

            let encoder = JSONEncoder()
            let data = try! encoder.encode(["top": value])
            set(data, forKey: key._key)

        }
    }
}
Jeehut commented 6 years ago

@calismatest Would you mind creating a PR with this solution?

@sunshinejr I'm not sure, but it seems to me that you are the current maintainer of this repo now. What do you think about this feature?

sunshinejr commented 6 years ago

Yes @Dschee, correct. There is a plan for new version at #154. It's in the works but basically Codable with default values is tricky so it takes a bit more time, but it's near.