Before Swift 3, you decode boolean values with NSCoder like this:
if let value = aDecoder.decodeObjectForKey(TestKey) as? Bool {
test = value
}
The suggested approach in Swift 3 is to use this instead:
aDecoder.decodeBool(forKey: TestKey)
But the class reference for decodeBool
doesn't explain how to handle the situation if the value you're decoding isn't actually a boolean. You can't embed decodeBool
in a let statement because the return value isn't an optional.
How do you safely decode values in Swift 3?
Took me a long time to figure out but you can still decode values like this. The problem I had with swift3 is the renaming of the encoding methods:
// swift2:
coder.encodeObject(Any?, forKey:String)
coder.encodeBool(Bool, forKey:String)
// swift3:
coder.encode(Any?, forKey: String)
coder.encode(Bool, forKey: String)
So when you encode a boolean with coder.encode(boolenValue, forKey: "myBool")
you have to decode it with decodeBool
but when you encode it like this:
let booleanValue = true
coder.encode(booleanValue as Any, forKey: "myBool")
you can still decode it like this:
if let value = coder.decodeObject(forKey: "myBool") as? Bool {
test = value
}
This is safe (for shorter code using nil-coalescing op.) when wanted to use suggested decodeBool.
let value = aDecoder.decodeObject(forKey: TestKey) as? Bool ?? aDecoder.decodeBool(forKey: TestKey)
Using decodeBool is possible in situations when sure that it's Bool, IMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With