使用泛型将对象转换为字典

Using generics to convert an object to a dictionary

我正在尝试从对象生成类似于 ["title": "a string", "id": 1] 的字典。我有两个对象客户和供应商。我想要一个像

这样的方法
func getDict<T>(values: [T]) -> [String: Any] {
    for value in values {
        value 
        // I don't know how to say sometime 
        // id is value.idSupplier or
        // sometime value.idCustommer
        // Same problem for title.
     }
}

一个对象的例子(简化版):

struct Customer {
    var idCustomer: Int
    var name: String?
}

struct Supplier {
    var idSupplier: Int
    var name: String?
}

有没有办法做到这一点,或者我误解了泛型?

除非您正在编写大量样板代码,否则您不能这样做,但这样您就无法从 if - else 子句中获益。

如果 属性 名称 idname 在两个结构中相同,您可以使用协议扩展

protocol ToDictionary {
    var id : Int { get }
    var name : String? { get }
}

extension ToDictionary {
    var dictionaryRepresentation : [String : Any] {
        return ["title" : name ?? "", "id" : id]
    }
}

然后在两个结构中采用协议

struct Customer : ToDictionary {
    var id: Int
    var name: String?
}

struct Supplier : ToDictionary {
    var id: Int
    var name: String?
}

现在你可以在任何采用协议

的结构中调用dictionaryRepresentation
let customer = Customer(id: 1, name: "Foo")
customer.dictionaryRepresentation // ["id": 1, "title": "Foo"]
let supplier = Supplier(id: 2, name: "Bar")
supplier.dictionaryRepresentation // ["id": 2, "title": "Bar"]

或者使用 Codable 协议,将实例编码为 JSON 或 属性 列表,然后将它们转换为字典。