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:
So when you encode a boolean with
coder.encode(boolenValue, forKey: "myBool")
you have to decode it withdecodeBool
but when you encode it like this:you can still decode it like this:
This is safe (for shorter code using nil-coalescing op.) when wanted to use suggested decodeBool.
Using decodeBool is possible in situations when sure that it's Bool, IMO.