[英]How to generate a dictionary in swift from an array
var tempsArray = [65,62,63,64,67,68,69,68,67,65,63,65,65]
func createCoordinates(temps: [Int]) -> Dictionary<Int, Int> {
var tempCoordinates = [Int: Int]()
for temperature in temps {
tempCoordinates[temperature] = temps[temperature]
}
return tempCoordinates
}
createCoordinates(tempsArray)
The goal is a function that takes an array of Ints as its only parameter and returns a dictionary of coordinates. 目标是一个函数,它将Int数组作为唯一参数并返回坐标字典。 In this case the goal is (0:65,1:62,2:63,...)
在这种情况下,目标是(0:65,1:62,2:63,......)
My code is not executing and is giving me an error of "Array index out of range" 我的代码没有执行,并且给我一个“数组索引超出范围”的错误
This is easy to achieve with enumerate()
: 使用
enumerate()
很容易实现:
let tempsArray = [65,62,63,64,67,68,69,68,67,65,63,65,65]
var dict = [Int:Int]()
for (index, value) in tempsArray.enumerate() {
dict[index] = value
}
print(dict)
Result: 结果:
[12: 65, 10: 63, 5: 68, 7: 68, 0: 65, 11: 65, 3: 64, 2: 63, 4: 67, 9: 65, 6: 69, 8: 67, 1: 62]
[12:65,10:63,5:68,7:68,0:65,11:65,3:64,2:63,4:67,9:65,6:69,8:67,1 :62]
Remember that dictionaries are unordered collections. 请记住,词典是无序的集合。
I believe it will be easy for you to adapt this simple example to your needs. 我相信你很容易根据自己的需要调整这个简单的例子。 If not, tell me where you're stuck and I'll help.
如果没有,告诉我你被困在哪里,我会帮忙。
More simple form: 更简单的形式:
tempsArray.reduce([Int:Int]()) {
(var d, v)->[Int:Int] in
d[d.count] = v
return d
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.