Let’s say I have array of objects that can be identified and I want to create dictionary from it. I can easily get tuples from my array like so:
比方说,我有一些可以被识别的对象,我想要从它创建字典。我可以很容易地从数组中获取元组,如下所示:
let tuples = myArray.map { return ($0.id, $0) }
But I can’t see initializer for dictionary to take array of tuples. Am I missing something? Do I have create extension for dictionary for this functionality (in fact it’s not hard but I thought it would be supplied by default) or there is easier way to do that?
但是我看不到字典的初始化器来获取元组数组。我遗漏了什么东西?我是否为这个功能创建了dictionary扩展(实际上它并不难,但我认为它是默认提供的)还是有更简单的方法来实现它?
There is code for extension
代码扩展
extension Dictionary
{
public init (_ arrayOfTuples : Array<(Key, Value)>)
{
self.init(minimumCapacity: arrayOfTuples.count)
for tuple in arrayOfTuples
{
self[tuple.0] = tuple.1
}
}
}
3 个解决方案
#1
5
Depending on what you want to do, you could:
取决于你想做什么,你可以:
let tuples = [(0, "0"), (1, "1"), (1, "2")]
var dictionary = [Int: String]()
Option 1: replace existing keys
选项1:替换现有的键
tuples.forEach {
dictionary[$0.0] = $0.1
}
print(dictionary) //prints [0: "0", 1: "2"]
Option 2: Don't allow repeting keys
选项2:不允许重复键
enum Errors: Error {
case DuplicatedKeyError
}
do {
try tuples.forEach {
guard dictionary.updateValue($0.1, forKey:$0.0) == nil else { throw Errors.DuplicatedKeyError }
}
print(dictionary)
} catch {
print("Error") // prints Error
}
#2
5
A generic approach:
/**
* Converts tuples to dict
*/
func dict<K,V>(_ tuples:[(K,V)])->[K:V]{
var dict:[K:V] = [K:V]()
tuples.forEach {dict[$0.0] = $0.1}
return dict
}
Functional programming update:
函数式编程更新:
func dict<K,V>(tuples:[(K,V)])->[K:V]{
return tuples.reduce([:]) {
var dict:[K:V] = $0
dict[$1.0] = $1.1
return dict
}
}
#3
2
Improved @GitSync answer using an extension.
使用扩展名改进@GitSync应答。
extension Array {
func toDictionary<K,V>() -> [K:V] where Iterator.Element == (K,V) {
return self.reduce([:]) {
var dict:[K:V] = $0
dict[$1.0] = $1.1
return dict
}
}
}
#1
5
Depending on what you want to do, you could:
取决于你想做什么,你可以:
let tuples = [(0, "0"), (1, "1"), (1, "2")]
var dictionary = [Int: String]()
Option 1: replace existing keys
选项1:替换现有的键
tuples.forEach {
dictionary[$0.0] = $0.1
}
print(dictionary) //prints [0: "0", 1: "2"]
Option 2: Don't allow repeting keys
选项2:不允许重复键
enum Errors: Error {
case DuplicatedKeyError
}
do {
try tuples.forEach {
guard dictionary.updateValue($0.1, forKey:$0.0) == nil else { throw Errors.DuplicatedKeyError }
}
print(dictionary)
} catch {
print("Error") // prints Error
}
#2
5
A generic approach:
/**
* Converts tuples to dict
*/
func dict<K,V>(_ tuples:[(K,V)])->[K:V]{
var dict:[K:V] = [K:V]()
tuples.forEach {dict[$0.0] = $0.1}
return dict
}
Functional programming update:
函数式编程更新:
func dict<K,V>(tuples:[(K,V)])->[K:V]{
return tuples.reduce([:]) {
var dict:[K:V] = $0
dict[$1.0] = $1.1
return dict
}
}
#3
2
Improved @GitSync answer using an extension.
使用扩展名改进@GitSync应答。
extension Array {
func toDictionary<K,V>() -> [K:V] where Iterator.Element == (K,V) {
return self.reduce([:]) {
var dict:[K:V] = $0
dict[$1.0] = $1.1
return dict
}
}
}