I have a function which saves primitives and objects confirming to NSCoding
to UserDefaults
.
func set(_ value: Any?, forKey key: String) {
if let value = value {
if (value is NSCoding) {
let encodedValue = NSKeyedArchiver.archivedData(withRootObject: value)
UserDefaults.standard.set(encodedValue, forKey: key)
} else {
print("Storage: failed to save value for key \(key). Value must confirm to NSCoding protocol")
}
} else {
UserDefaults.standard.removeObject(forKey: key)
}
}
I want to get rid of the conformance check inside the function. So the function must accept only NSCoding
values.
I’ve tried to change the function's signature to this:
func set(_ value: NSCoding?, forKey key: String)
And this:
func set<T: Any>(_ value: T?, forKey key: String) where T: NSCoding
However, I get a compile error in every function call.
In the first case I get:
Argument type ‘***’ does not conform to expected type 'NSCoding?'
In the second:
Cannot convert value of type '***' to expected argument type '_?'
What should I change to make it work?