For an example like:
someOptionalDouble = aDecoder.decodeDouble(forKey: "SomeKey")
I'm not sure how to avoid a crash if the double was encoded as nil, while also avoiding Apple's console warning that decoding primitives as an object will become an error in the future.
I tried an approach
extension NSCoder {
func decodeOptionalDouble(forKey key: String) -> Double? {
guard self.containsValue(forKey: key) else { return nil }
return self.decodeDouble(forKey: key)
}
}
But encounter an error
Error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver decodeDoubleForKey:]: value for key (SomeKey) is not a 64-bit float" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver decodeDoubleForKey:]: value for key (SomeKey) is not a 64-bit float}.
The optional double property is encoded with func encode(_ object: Any?, forKey key: String).
wes1
(Wes)
2
Outside NSCoder, on the decode side, there's a separate API, decodeIfPresent, for optionals - e.g.,
let container = try decoder.container(keyedBy: CodingKeys.self)
self.score = try container.decodeIfPresent(Int.self, forKey: .ckScore)