假设我有可以识别的对象数组,我想从中创建字典。我可以很容易地从我的数组中获取元组:
let tuples = myArray.map { return ($0.id, $0) }
但是我看不到字典的初始化器来获取元组数组。我错过了什么吗?我是否为此功能创建了字典扩展(事实上它并不难,但我认为默认情况下会提供)或者有更简单的方法吗?
有扩展代码
extension Dictionary
{
public init (_ arrayOfTuples : Array<(Key, Value)>)
{
self.init(minimumCapacity: arrayOfTuples.count)
for tuple in arrayOfTuples
{
self[tuple.0] = tuple.1
}
}
}
答案 0 :(得分:26)
快捷键4
如果您的元组是(Hashable,String),则可以使用:
let array = [("key1", "value1"), ("key2", "value2"), ("key3", "value3")]
let dictionary = array.reduce(into: [:]) { $0[$1.0] = $1.1 }
print(dictionary) // ["key1": "value1", "key2": "value2", "key3": "value3"]
答案 1 :(得分:7)
根据您的目的,您可以:
let tuples = [(0, "0"), (1, "1"), (1, "2")]
var dictionary = [Int: String]()
选项1:替换现有密钥
tuples.forEach {
dictionary[$0.0] = $0.1
}
print(dictionary) //prints [0: "0", 1: "2"]
选项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)
/**
* 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
}
功能编程更新:
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)
使用扩展程序改进了@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
}
}
}
答案 4 :(得分:2)
您可以使用Dictionary的本机init函数:
plugins {
id 'java'
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.cloud:google-cloud-monitoring:1.48.0'
// exception with the dependency below
compile 'com.google.cloud.dataflow:google-cloud-dataflow-java-sdk-all:2.5.0'
}
答案 5 :(得分:0)
更新为@Stefan答案。
extension Array {
func toDictionary<K, V>() -> [K: V] where Iterator.Element == (K, V) {
return Dictionary(uniqueKeysWithValues: self)
}
}