gpt4 book ai didi

arrays - 将值放入带有数组数据的字典中 - swift

转载 作者:行者123 更新时间:2023-11-30 13:42:32 26 4
gpt4 key购买 nike

我真的不明白 - 为什么这不起作用?

var listOfFruit = ["Apple", "Banana","Lemon"]
var emptyDict = [String: String]()
var key = ["Name of Fruit","Name of Fruit","Name of Fruit"]

func createDictionary(){
var index: Int
index = listOfFruit.count

for index in listOfFruit {
emptyDict = [key[index]:listOfFruit[index]]
print (emptyDict)
}
}

我得到了平常的结果:

最佳答案

我试图猜测您需要什么,因为您的问题很不清楚。

如果给定此输入

var fruits = ["Apple", "Banana","Lemon"]
var keys = ["Name of Fruit", "Name of Fruit", "Name of Fruit"]

你想要这个输出

["Name of Fruit 2": "Lemon", "Name of Fruit 0": "Apple", "Name of Fruit 1": "Banana"]

然后你就可以使用这个代码

let dict = zip(fruits, keys).enumerate().reduce([String:String]()) { (var result, elm) -> [String:String] in
let key = "\(elm.element.1) \(elm.index)"
let value = elm.element.0
result[key] = value
return result
}

或者这段代码

assert(keys.count == fruits.count)
var dict = [String:String]()
for i in 0..<fruits.count {
let key = "\(keys[i]) \(i)"
let value = fruits[i]
dict[key] = value
}

关于arrays - 将值放入带有数组数据的字典中 - swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35388683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com