尝试将结构数组保存到 UserDefaults 时出错

Error by trying to save array of structs to UserDeafults

在网站上的另一个 post 中找到此示例代码

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,class 实现 NSCoding 协议必须包括 init?(coder: NSCoder)encode(with: NSCoder) 方法。

在你的代码中,我看到 encodeWithCoder(aCoder: NSCoder)。将其更改为 encode(with: NSCoder) 并且代码有效。