forEach
let numbers=[Int](0...7)
numbers.forEach{
(num) in
if(num==3){
return
}
print(num)
}
for in
for in可以说比forEach好用太多
let numberList = [1,2,3,4,5]
var result = ""
for num in numberList {
result += "\(num) "
}
enumerated
普通的for循环无法拿到索引,通过关键字enumerated()可以拿到索引
let numbers=[Int](0...7)
for (index,num) in numbers.enumerated(){
print("the index is :\(index)")
print(num)
}
迭代器遍历
let numbers=[Int](0...7)
var numInerator = numbers.makeIterator()
while let num = numInerator.next() {
print(num)
}
indices
讲到遍历就离不开索引,startIndex 返回第一个元素的位置,对于数组来说,永远都是0,endIndex 返回最优一个元素索引+1的位置等同于count,如果数组为空,startIndex 等于endeIndex
enumerated获取了索引和值
那么如果我们想只遍历索引呢,可以使用indices获取数组的索引区间
let numbers = [Int](2...7)
for i in numbers.indices{
print(numbers[i])
}
Range
let numbers = [Int](2...7)
for i in 0...(numbers.count-1)
print(numbers[i])
}
弃用
首先说一下,Swift 3.0 版本将会去掉沿用已经的 C 风格循环语法,以后此语法不会再swift中出现
for var i = 0; i < numberList.count; i++ {
}
网友评论