JSON编码自定义类型(协议)

时间:2018-12-02 00:14:58

标签: swift

我正在尝试对(具有JSON的)对象进行编码,该对象的属性符合自定义协议的类型。尽管自定义协议似乎符合ambiguous reference to member 'encode(_:forKey:)',但仍会导致编译错误Encodable

为什么模棱两可?我只能看到一个可能的候选者,但是编译器却认为不是。

感谢您提供的任何帮助!

import Foundation

//
// Name
//

enum NameCodingKeys: String, CodingKey {
    case first, last
}

public protocol Name: Encodable {
    var first: String { get }
    var last: String { get }
}

extension Name {
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: NameCodingKeys.self)
        try container.encode(first, forKey: .first)
        try container.encode(last, forKey: .last)
    }
}

public struct DefaultName: Name {
    public var first: String
    public var last: String
}

//
// Person
//

enum PersonCodingKeys: String, CodingKey {
    case name
}

public protocol Person: Encodable {
    var name: Name { get }
}

extension Person {
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: PersonCodingKeys.self)
        try container.encode(name, forKey: .name) // error: ambiguous reference to member 'encode(_:forKey:)'
    }
}

public struct DefaultPerson: Person {
    public var name: Name
}

//
// Encode
//

let encoder = JSONEncoder()
let person = DefaultPerson(name: DefaultName(first: "John", last: "Smith")) // Should be: let person: Person = ...
let json = String(data: try! encoder.encode(person), encoding: .utf8)!
print(json)

0 个答案:

没有答案