将2个数组组合成Xcode 6中的字典,swift?和相应的索引值) [英] Combining 2 arrays into a dictionary in Xcode 6, swift?, with corresponding index values)
问题描述
score == [1,2,3,4,5 ,6,7,8,9]
dates == [7/12/15,7/12/15,7/12/15,7/12/15, 7/13/15,7/13/15,7/13/15,7/13/15,7/14/15]
我想要发生的是在viewDidLoad()中创建的。
var scoreDatesDictionary = [
7/12/15:[1,2,3,4]
7/13/15:[5,6 ,7,8]
7/14/15:[9]
]
在本质上,两个数组具有相应的值,(firstArray [0])对应于(secondArray [0])。我试图在secondArray(日期)中使用相同的字符串在字典中与其相应的索引值进行匹配。我可能没有什么意义,但我提供的示例代码应该可以工作。我花了很多时间来处理这个问题,我找不到解决方案。
,这里是一个使用枚举
和 nil coalescing运算符 ??
的版本更干净地执行此操作:
对于 Swift 1.2:
code> let score = [1,2,3,4,5,6,7,8,9]
let dates = [7/12/15,7/12/15 15年7月12日, 15年7月12日, 15年7月13日, 15年7月13日, 15年7月13日, 15年7月13日, 7/14/15]
var dic = [String:[Int]]()
(枚举中的(索引,日期)){
dic [date ] =(dic [date] ?? [])+ [score [index]]
}
print(dic)// prints[7/12/15:[1,2,3, 4],7/14/15:[9],7/13/15:[5,6,7,8]]
对于 Swift 2.0 ,您需要使用 dates.enumerate()
。
In my app, I have 2 arrays which are in use a lot, an array that stores score values as an Integer, and another array that stores dates in the format "mm/dd/yy". These arrays are continuously being appended, and the indexes of these arrays correspond to each other, for example, index 0 of dates array corresponds to index 0 of score array. I want these arrays to be turned into a dictionary upon when a second screen loads(these are global variables). For example, these are the type of values in each array.
score == [1,2,3,4,5,6,7,8,9]
dates == ["7/12/15","7/12/15","7/12/15","7/12/15","7/13/15","7/13/15","7/13/15","7/13/15"," 7/14/15"]
What I want to happen, is that upon viewDidLoad(), this gets created.
var scoreDatesDictionary = [
"7/12/15": [1,2,3,4]
"7/13/15": [5,6,7,8]
"7/14/15": [9]
]
In its essence, the two arrays have corresponding values, (firstArray[0]) corresponds to (secondArray[0]). I am trying to make it that in the secondArray(dates), identical strings get matched up in a dictionary with their corresponding index values. I may not make much sense, but the sample code I provided should work. I spent a lot of time working with this, and I can't find a solution.
Working off @Leo's correct answer, here's a version that makes use of enumerate
and the nil coalescing operator ??
to do this more cleanly:
For Swift 1.2:
let score = [1,2,3,4,5,6,7,8,9]
let dates = ["7/12/15","7/12/15","7/12/15","7/12/15","7/13/15","7/13/15","7/13/15","7/13/15"," 7/14/15"]
var dic = [String:[Int]]()
for (index, date) in enumerate(dates) {
dic[date] = (dic[date] ?? []) + [score[index]]
}
print(dic) // prints "[7/12/15: [1, 2, 3, 4], 7/14/15: [9], 7/13/15: [5, 6, 7, 8]]"
For Swift 2.0, you need to use dates.enumerate()
instead.
这篇关于将2个数组组合成Xcode 6中的字典,swift?和相应的索引值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!