今天把Swift 项目升级到了 Swift 3.0,好多坑啊,for 循环都抛弃C 语言风格了,让我看看 Swift 3.0 for 循环 的用法吧
被抛弃的C语言风格,如下
for var i = 0;i<4;i++{
}
Swift 3.0 的用法
- 简单次数循环
// 利用循环 拼接 字符串
var ss = ""
for i in 0...10 {
ss += "\(i)"
}
print("ss: " + ss)
- 遍历数组
let array = ["1","2","3","4","5"]
var ss = ""
for aa in array {
ss += aa
}
print("ss: " + ss)
- 得到数组索引
let array = ["1","2","3","4","5"]
var sb = ""
// 如果想知道 索引 怎么办呢
for bb in array.enumerated() {
sb += "[\(bb.offset)]\(bb.element)"
}
print("sb: " + sb)
// 还可以再改写一下
var ssb = ""
for (index, item) in array.enumerated() {
ssb += "[\(index)]\(item)"
}
print("ssb: " + ssb)
4.逆序 遍历
let array = ["1","2","3","4","5"]
// let array33 = [1,2,3,5]
var sb = ""
for bb in array.enumerated().reversed() {
// \ 后面加 () 小括号里 可以写代码(变量表达式)
sb += "[\(bb.offset)]\(bb.element)"
}
print("sb: " + sb)
5.根据条件 取 数组元素
//取出 索引 是2 的倍数的元素
let array = ["1","2","3","4","5"]
// let array33 = [1,2,3,5]
var sb = ""
for bb in array.enumerated().filter({ (index, item) in index % 2 == 0
}) {
// \ 后面加 () 小括号里 可以写代码(变量表达式)
sb += "[\(bb.offset)]\(bb.element)"
}
print("sb: " + sb)
6.还有一种
let array = ["1","2","3","4","5"]
for i in 0..<array.count{
print(array[i])
}