所以我在这里找到了这样做的方法,但我不明白如何实现它。
extension Collection {
var indexedDictionary: [Int: Element] {
return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
}
}
所以假设我有一个像
这样的字符串数组var someArray: [String] = ["String", "String", "String"...etc]
我希望被编入索引,使最终结果成为像
这样的字典 [1: "string", 2: "string":..etc]
使用该方法,我该如何实现?就像我将someArray放在那里的代码一样?
答案 0 :(得分:2)
此扩展程序:
extension Collection {
var indexedDictionary: [Int: Element] {
return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
}
}
将indexedDictionary
属性添加到Swift中的所有Collection
。数组是Collection
,因此当您将此扩展添加到顶级的Swift源文件时,数组会将此属性添加到它们中(不要将其放在另一个class
内,{{1 },或struct
)。您只需将此项添加到项目中的一个文件中,然后就可以在每个文件中访问新属性。
然后,您只需在代码中的任何数组上调用enum
,它就会返回类型为indexedDictionary
的{{1}},其中Dictionary
表示原始数组中的类型。因此,如果名为[Int : Element]
的数组属于Element
类型,则myArray
将返回类型为[String]
的{{1}}。
<强>示例:强>
myArray.indexedDictionary
输出:
Dictionary
[Int : String]
输出:
let arr1 = ["a", "b", "c"] let dict1 = arr1.indexedDictionary print(dict1)
[2: "c", 0: "a", 1: "b"]
输出:
// It works with dictionary literals let dict2 = [5, 10, 15].indexedDictionary print(dict2)
注意:字典是无序的,因此即使订单不可预测,键值与值的映射也是您所期望的。
答案 1 :(得分:1)
let result = someArray.reduce([:]) { (dic, val) -> [Int:String] in
let index = someArray.index(of: val)
var mutableDic = dic
mutableDic[index!] = val
return mutableDic
}