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?