我想创建一个像这样的数组
array=["1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8"]
它类似于字典,每个值都需要key:value
对,
所以我的问题是如何初始化这种类型的数组?以下是我的工作,它没有用。
array=[String:String]()
for i in 0...7{
array.append(String(i):String(i))
}
每一行都有一个错误!!
plz help
答案 0 :(得分:0)
它不像Dictionary
Dictionary
,如果你想制作一本字典就可以这样。
var dictionary = [String:String]()
for i in 0...7{
dictionary[String(i)] = String(i)
}
print(dictionary)
["0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7"]
答案 1 :(得分:0)
除了Nirav D的回答;我觉得以下内容可能有所帮助:
有一种方法updateValue(_:forKey:)
可以更新(或在键不存在时添加新的键值对)给定键的值。
所以你的代码看起来像这样:
var array = [String:String]()
for i in 0...7 {
array.updateValue(String(i), forKey: String(i))
}
print(array)
// Output
["2": "2", "1": "1", "6": "6", "4": "4", "3": "3", "7": "7", "0": "0", "5": "5"]
Swift总是令人惊叹,您可以定义+=
运算符,使其更容易。所以代码如下:
// Defining += operator
func += <K, V> (inout left: [K:V], right: [K:V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
// Usage
var array = [String:String]()
for i in 0...7{
array += [String(i):String(i)]
}
print(array)
// Output
["2": "2", "1": "1", "6": "6", "4": "4", "3": "3", "7": "7", "0": "0", "5": "5"]