[英]Create dictionary from an array of objects using property of object as key for the dictionary?
With Swift is it possible to create a dictionary of [String:[Object]] from an array of objects [Object] using a property of those objects as the String key for the dictionary using swift's "map"? 使用Swift可以使用swift的“map”使用这些对象的属性作为字典的String键,从对象数组[Object]创建[String:[Object]]的字典?
class Contact:NSObject {
var id:String = ""
var name:String = ""
var phone:String = ""
init(id:String, name:String, phone:String){
self.id = id
self.name = name
self.phone = phone
}
}
var contactsArray:[Contact]
var contactsDict:[String:Contact]
contactsDict = (contactsArray as Array).map { ...WHAT GOES HERE... }
Let's say you want to use id
as the key for the dictionary: 假设你想使用id
作为字典的键:
var contactsArray = [Contact]()
// add to contactsArray
var contactsDict = [String: Contact]()
contactsArray.forEach {
contactsDict[$0.id] = $0
}
The difference between map
and forEach
is that map
returns an array. 之间的差map
和forEach
是map
返回一个数组。 forEach
doesn't return anything. forEach
不会返回任何内容。
You can achieve this via reduce
in a one-line functional-style code: 您可以通过reduce
单行功能样式代码来实现此目的:
let contactsDict = contactsArray.reduce([String:Contact]()) { var d = $0; d[$1.id] = $1; return d; }
This also keeps contactsDict
immutable, which is the preferred way to handle variables in Swift. 这也使contactsDict
不可变,这是在Swift中处理变量的首选方法。
Or, if you want to get fancy, you can overload the +
operator for dictionaries, and make use of that: 或者,如果你想获得幻想,你可以重载字典的+
运算符,并使用它:
func +<K,V>(lhs: [K:V], rhs: Contact) -> [K:V] {
var result = lhs
result[rhs.0] = rhs.1
return result
}
let contactsDict = contacts.reduce([String:Contact]()) { $0 + ($1.id, $1) }
Swift 4 斯威夫特4
There's now a direct way to do this: 现在有一种直接的方法可以做到这一点:
https://developer.apple.com/documentation/swift/dictionary/2919592-init https://developer.apple.com/documentation/swift/dictionary/2919592-init
It's an initializer for Dictionary that lets you return a string key for each element in a Collection that specifies how it should be grouped in the resulting Dictionary. 它是Dictionary的初始化程序,它允许您为Collection中的每个元素返回一个字符串键,指定如何在生成的Dictionary中对其进行分组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.