Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3: Safe way to decode values with NSCoder?

Tags:

swift

swift3

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?

like image 409
Crashalot Avatar asked Sep 23 '16 08:09

Crashalot


2 Answers

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
}
like image 107
errnesto Avatar answered Nov 15 '22 08:11

errnesto


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.

like image 6
pedrouan Avatar answered Nov 15 '22 08:11

pedrouan