How to encode Int as an optional using NSCoding

后端 未结 1 395
孤城傲影
孤城傲影 2021-01-01 23:17

I am trying to declare two properties as optionals in a custom class - a String and an Int.

I\'m doing this in MyClass:

var myString: String?
var my         


        
相关标签:
1条回答
  • 2021-01-02 00:07

    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.

    0 讨论(0)
提交回复
热议问题