本文主要是介绍Swift enumerate函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本文的Swift语言版本,1.2
先看看问题
把这两个数组合成一个字典
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"]
期望的合成后结果
var scoreDatesDictionary = [
"7/12/15": [1,2,3,4]
"7/13/15": [5,6,7,8]
"7/14/15": [9]
]
我给出的答案:能解决问题,但是不够优雅,不够简洁,因为我对Swift很多global的函数掌握的不是很好,最近开发项目还是用OC。以后遇到了我没掌握好的,就用博客记录下来。
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 var index=0;index < dates.count; index++ {let key = dates[index];var value = dic[key]if value == nil{dic[key] = [score[index]]}else{value!.append(score[index])dic[key] = value}}println(dic)
参考答案
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]]"
enumerate 函数-Swift 1.2
遍历数组和字符串的方式,同时返回index以及数据
let str = "Wenchen"for (index,character) in enumerate(str){println("\(index):\(character)")}
输出
0:W
1:e
2:n
3:c
4:h
5:e
6:n
遍历数组的例子
let myArray = ["Wen","Chen","Huang"]for (index,str) in enumerate(myArray){println("\(index):\(str)")}
输出
0:Wen
1:Chen
2:Huang
这篇关于Swift enumerate函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!