sunshinejr / SwiftyUserDefaults

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

How can I make it support NSColor? #157

Closed GnohiSiaM closed 5 years ago

GnohiSiaM commented 6 years ago

Hi there! I tried to extend NSColor:

extension NSColor: DefaultsSerializable {

    public static func get(key: String, userDefaults: UserDefaults) -> NSColor? {
        guard let data = userDefaults.data(forKey: key) else { return nil }
        return NSKeyedUnarchiver.unarchiveObject(with: data) as? NSColor
    }

    public static func getArray(key: String, userDefaults: UserDefaults) -> [NSColor]? {
        return userDefaults.data(forKey: key).flatMap(NSKeyedUnarchiver.unarchiveObject) as? [NSColor]
    }

    public static func save(key: String, value: NSColor?, userDefaults: UserDefaults) {
        guard let value = value else {
            userDefaults.removeObject(forKey: key)
            return
        }

        userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
    }

    public static func saveArray(key: String, value: [NSColor], userDefaults: UserDefaults) {
        userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
    }

}

and got these errors:

Method 'get(key:userDefaults:)' in non-final class 'NSColor' must return `Self` to conform to protocol 'DefaultsGettable'
Protocol 'DefaultsGettable' requirement 'getArray(key:userDefaults:)' cannot be satisfied by a non-final class ('NSColor') because it uses 'Self' in a non-parameter, non-result type position
Protocol 'DefaultsStoreable' requirement 'saveArray(key:value:userDefaults:)' cannot be satisfied by a non-final class ('NSColor') because it uses 'Self' in a non-parameter, non-result type position

Is it possible to add support for non-final class?

sunshinejr commented 6 years ago

Hey @GnohiSiaM, could you please try with replacing NSColor in the extension with Self? The problem here is that NSColor is not final, someone could create a subclass, thus returning NSColor is not dynamic enough 😄

GnohiSiaM commented 6 years ago

@sunshinejr I have tried it, but it still not work 'Self' is only available in a protocol or as the result of a method in a class

sunshinejr commented 6 years ago

Oh, that's an unfortunate limitation... I'm gonna think about the solution and let you know @GnohiSiaM.

sunshinejr commented 6 years ago

As an update, I was trying multiple things to make a workaround for this one, but unfortunately nothing stood out as a perfect solution. I would use some help if anyone would like to play with resolving the non-final case scenario.

robcecil commented 6 years ago

Yeah, need a solution for non-final classes. I'm dealing with objc code generated by a thirdparty tool. If I can't find a solution then I will have to go back to version 3.

robcecil commented 5 years ago

Bump.