This question already has an answer here:
Does not conform to protocol 'NSCoding' - Swift 3
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
在网站上的另一则帖子中找到了此示例代码

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")
        }

    }
}


我试图弄清楚它是如何工作的,但是它具有以下错误:type 'Foo.Encoding' does not conform to protocol 'NSCoding'。我不知道这是从swift到swift 3的变化,但没有像其他行中那样自动修复。我的代码有什么问题?

最佳答案

根据documentation,实现NSCoding协议的类必须包含init?(coder: NSCoder)encode(with: NSCoder)方法。

在您的代码中,我看到了encodeWithCoder(aCoder: NSCoder)。将其更改为encode(with: NSCoder),代码将起作用。

09-06 11:42