目录
- forEach
- for in
- enumerated
- 迭代器遍历
- indices
- enumerated获取了索引和值
- Range
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++ {
}
以上就是Swift之for循环的基础使用学习的详细内容,更多关于Swift基础for循环的资料请关注其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)