ylliX - Online Advertising Network

Swift 3: Unexpected nil when using NSCoder

If you were using NSCoder in Swift 2, I’m pretty sure you used such code:

decoder.decodeObject(forKey: "name") as! String
decoder.decodeObject(forKey: "number") as! Int

Now, in Swift 3, using such construction, will cause:

fatal error: unexpectedly found nil while unwrapping an Optional value

So is there any solution for this? Yes, you need to use explicit methods to integers, floats, bools and some other types. Just rewrite this code as:
decoder.decodeObject(forKey: "name") as! String
decoder.decodeInteger(forKey: "number")

And this error will be gone. Available methods below:
decodeBool
decodeInteger
decodeCInt (returns Int32)
decodeInt32
decodeInt64
decodeFloat
decodeDouble
decodeBytes

Leave a Reply