作者:Erica Sadun,原文鏈接,原文日期:2015/09/01
譯者:小鐵匠Linus;校對:千葉知風;定稿:shanks
Mike T. 私信我,如何讓 for 循環(huán)從下標 i (比如 5 )開始,而不是從 0 開始。
Swift 2.0 提供了一種像 C 語言那樣的循環(huán),代碼如下:
for var index = 5; index < array.count; index++ {
// do something with array[index]
}
也可以用區(qū)間運算符的方式實現(xiàn)相似的功能:
for index in 5..<array.count {
// do something with array[index]
}
甚至可以用forEach這樣寫:
(5..<array.count).forEach {
// do something with array[$0]
}
你也可以截取數(shù)組中你需要使用的部分進行遍歷,每次遍歷時可以獲取數(shù)組下標(本例中偏移量為 5,也可以看看另一篇講 slice enumeration 的文章)和對應的值。
for (index, value) in array[5..<array.count].enumerate() {
// do something with (index + 5) and/or value
}
如果你想要更準確的計數(shù),而不必每次都加上偏移量 5 的話,可以使用zip,例子如下:
let range = 5..<array.count
for (index, value) in zip(range, array[range]) {
// use index, value here
}
也可以調整zip方法,將其應用在forEach里:
let range = 5..<array.count
zip(range, array[range]).forEach {
index, value in
// use index, value here
}
當然,你也可以使用map來處理子區(qū)間的值。不像forEach,map會在閉包里返回一個新的值。
let results = array[range].map({
// transform $0 and return new value
})
如果你不想遍歷數(shù)組前 5 個元素,可以使用dropFirst()從剩余的元素開始遍歷。下面這個例子沒有使用下標,如果需要的話可以按前面提到的方法去獲取。
for value in array.dropFirst(5) {
// use value here
}
使用removeFirst()可以返回數(shù)組片(slice)第一個元素,然后該元素會從數(shù)組片中刪除。接下來的代碼段結合了removeFirst()和dropFirst(),首先去掉前5個元素,然后遍歷數(shù)組剩余的元素。
var slice = array.dropFirst(5)
while !slice.isEmpty {
let value = slice.removeFirst()
// use value here
}
另外也有很多方式可以遍歷數(shù)組,包括在需要的時候才去獲取數(shù)組切片的值(使用lazy進行延遲加載),但是以上提到的方法已經(jīng)基本夠用了。
感謝 Mike Ash,并且一定要去看看 Nate Cook 的解決方案。