Generics 使用泛型将对象转换为字典
我试图从对象生成一个类似于[title:a string,id:1]的字典。我有两个目标客户和供应商。我想有一个这样的方法Generics 使用泛型将对象转换为字典,generics,swift4,swift-protocols,Generics,Swift4,Swift Protocols,我试图从对象生成一个类似于[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
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.
}
}
有没有办法做到这一点,或者我可能误解了泛型?除非您编写了大量的样板代码,否则您无法做到这一点,但是如果使用if-else子句,则没有任何好处 如果两个结构中的属性名称id和名称相同,则可以使用协议扩展
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"]
或者使用可编码协议,将实例编码为JSON或属性列表,然后将其转换为字典。@vadian从我的对象、值类型,我正在用一个示例更新我的问题。这是我的问题,如何以一种通用的方式获取密钥我写了一个答案。不是我期望的答案,但我理解,谢谢你的帮助!
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"]