Swift之for循環(huán)的基礎使用學習
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循環(huán)無法拿到索引,通過關鍵字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 返回第一個元素的位置,對于數(shù)組來說,永遠都是0,endIndex 返回最優(yōu)一個元素索引+1的位置等同于count,如果數(shù)組為空,startIndex 等于endeIndex
enumerated獲取了索引和值
那么如果我們想只遍歷索引呢,可以使用indices獲取數(shù)組的索引區(qū)間
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 版本將會去掉沿用已經(jīng)的 C 風格循環(huán)語法,以后此語法不會再swift中出現(xiàn)
for var i = 0; i < numberList.count; i++ { }
以上就是Swift之for循環(huán)的基礎使用學習的詳細內容,更多關于Swift基礎for循環(huán)的資料請關注腳本之家其它相關文章!
相關文章
Swift如何調用Objective-C的可變參數(shù)函數(shù)詳解
這篇文章主要給大家介紹了關于Swift如何調用Objective-C的可變參數(shù)函數(shù)的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用swift具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2018-03-03