How to encode Int as an optional using NSCoding How to encode Int as an optional using NSCoding xcode xcode

How to encode Int as an optional using NSCoding


If it can be optional, you will have to use encodeObject for it, too.

You are using an Objective-C framework and Objective-C allows nil only for objects (class/reference types). An integer cannot be nil in Objective-C.

However, if you use encodeObject, Swift will automatically convert your Int to NSNumber, which can be nil.

Another option is to skip the value entirely:

if let myIntValue = myInt {    aCoder.encodeInteger(myIntValue, forKey: "MyInt")}

and use containsValueForKey(_:) when decoding.