Why is my Swift 3.0 decodeInteger decoder not working for integers?

So, we used the groups to save and retrieve some data on the extension and the main application, and everything worked fine for Swift 2.3, but then we upgraded to Swift 3.0 and got some problems.

The current implementation, which gives us problems, is as follows:

open class SomeClass: NSObject, NSCoding {
  open var someVar: Int!

  open func encode(with aCoder: NSCoder) {
    aCoder.encode(self.someVar, forKey:"someVar")
  }

  public required convenience init?(coder decoder: NSCoder) {
    // this is where it breaks
    self.someVar = decoder.decodeInteger(forKey: "someVar") 
  }

}

The following error is raised:

*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeInt32ForKey:]: value for key (someVar) is not an integer number'

It's funny that the old Swift 2.3 implementation works without any problems: self.someVar = decoder.decodeObject(forKey: "someVar") as! Int(I realized from other posts that this won't work ...)

So what can I do wrong? It should be said that the original value is retrieved from the float and executed in int.

+4
source share
2 answers

Swift 3.

Swift 3 encode . :

encode(Any?, forKey: String)

encode(Int, forKey: String)

( Swift 2 , ).

Int!. Implicitly Unwrapped Optionals Swift 3 - Swift Evolution 0054.

, , IUO , Any? , Int.

! , IUO; , , (1) , (2) , , . ( , @_autounwrapped.)

​​

aCoder.encode(self.someVar!, forKey:"someVar")
+7

, swift, ,   aDecoder.decodeObject(forKey: "someVar")

,

aDecoder.decodeObject(forKey: "age") as? Int ?? aDecoder.decodeInteger(forKey: "age")

, , , "someVar"

+4

Source: https://habr.com/ru/post/1657502/


All Articles