Simple Swift class does not compile

对着背影说爱祢 提交于 2019-12-01 21:10:31

As I point out in comments, your example seems to compile fine on beta 2, although it still won't work for a couple of reasons, for encoderWithCoder to be of any use, ClassWithOneArray needs to:

  1. declare conformance with NSCoding,
  2. implement NSCoding,
  3. inherit from NSObject or implement NSObjectProtocol, and,
  4. use a non-mangled name.

All told, that means:

@objc(ClassWithOneArray)
class ClassWithOneArray:NSObject, NSCoding {
    var myArray: String[]
    init(myArray: String[]) {
        self.myArray = myArray
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myArray, forKey: "myArray")
    }
    init(coder aDecoder: NSCoder) {
        self.myArray = aDecoder.decodeObjectForKey("myArray") as String[]
    }
}

Also it seems as if the simple methods of testing archiving aren't available in the playground, probably because the classes don't get properly registered.

let foo = ClassWithOneArray(myArray:["A"])

let data = NSKeyedArchiver.archivedDataWithRootObject(foo)

let unarchiver = NSKeyedUnarchiver(forReadingWithData:data)
unarchiver.setClass(ClassWithOneArray.self, forClassName: "ClassWithOneArray")
let bar = unarchiver.decodeObjectForKey("root") as ClassWithOneArray

It looks like your syntax is a bit off for what you're trying to accomplish - something like this should work:

class ClassWithOneInt {
    var myInt: Int
    init(myInt: Int) {
        self.myInt = myInt
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myInt, forKey: "myInt")
    }
    init(coder aDecoder: NSCoder) {
        self.myInt = aDecoder.decodeObjectForKey("myInt") as Int
    }
}

class ClassWithOneArray {
    var myArray: String[]
    init(myArray: String[]) {
        self.myArray = myArray
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myArray, forKey: "myArray")
    }
    init(coder aDecoder: NSCoder) {
        self.myArray = aDecoder.decodeObjectForKey("myArray") as String[]
    }
}

In my experience simply declaring the Protocol "NSCoding" to your class should do the trick. Hope this helps someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!