0

Found this example code in another post on the site

struct Foo {
    var a : String
    var b : String?
}

extension Foo {
    init?(data: NSData) {
        if let coding = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? Encoding {
            a = coding.a as String
            b = coding.b as String?
        } else {
            return nil
        }
    }

    func encode() -> NSData {
        return NSKeyedArchiver.archivedData(withRootObject: Encoding(self)) as NSData
    }

    private class Encoding: NSObject, NSCoding {    //Here is the error
        let a : NSString
        let b : NSString?

        init(_ foo: Foo) {
            a = foo.a as NSString
            b = foo.b as NSString?
        }

        @objc required init?(coder aDecoder: NSCoder) {
            if let a = aDecoder.decodeObject(forKey: "a") as? NSString {
                self.a = a
            } else {
                return nil
            }
            b = aDecoder.decodeObject(forKey: "b") as? NSString
        }

        @objc func encodeWithCoder(aCoder: NSCoder) {
            aCoder.encode(a, forKey: "a")
            aCoder.encode(b, forKey: "b")
        }

    }
}

I am trying to figure out how it works but it has the following error:type 'Foo.Encoding' does not conform to protocol 'NSCoding'. I dont know if it is a change from swift to swift 3 but there is no auto fix it as in other lines. What is wrong in my code?

Alex Karapanos
  • 895
  • 2
  • 7
  • 20
  • Another one here: [Swift: Does not conform to protocol NSCoding](http://stackoverflow.com/questions/25750088/swift-does-not-conform-to-protocol-nscoding). – Martin R Nov 13 '16 at 18:57

1 Answers1

0

According to documentation, class implementing NSCoding protocol must include init?(coder: NSCoder) and encode(with: NSCoder) methods.

In your code, I see encodeWithCoder(aCoder: NSCoder). Change it to encode(with: NSCoder) and the code works.

Erik Cupal
  • 2,735
  • 1
  • 19
  • 20