加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 2.0实战:如何实现从非零下标遍历数组?

发布时间:2020-12-14 02:41:15 所属栏目:百科 来源:网络整理
导读:如何让 for 循环从下标 i(比如 5)开始,而不是从 0 开始。 Swift 2.0 提供了一种像 C 语言那样的循环,代码如下: for var index = 5 ; index array. count ; index ++ { // do something with array[index] } 也可以用区间运算符的方式实现相似的功能: f

如何让 for 循环从下标 i(比如 5)开始,而不是从 0 开始。

Swift 2.0 提供了一种像 C 语言那样的循环,代码如下:

for var index = 5; index < array.count; index++ {  
  // do something with array[index] 
}

也可以用区间运算符的方式实现相似的功能:

for index in 5..<array.count {  
 // do something with array[index]  
}

甚至可以用forEach这样写:

(5..<array.count).forEach {  
    // do something with array[$0]  
}

你也可以截取数组中你需要使用的部分进行遍历,每次遍历时可以获取数组下标(本例中偏移量为 5,也可以看看 另一篇讲 slice enumeration 的文章)和对应的值。

for (index,value) in array[5..<array.count].enumerate() {  
  // do something with (index + 5) and/or value  
}

如果你想要更准确的计数,而不必每次都加上偏移量 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来处理子区间的值。不像forEach,map会在闭包里返回一个新的值。

let results = array[range].map({  
    // transform $0 and return new value  
})

如果你不想遍历数组前 5 个元素,可以使用dropFirst()从剩余的元素开始遍历。下面这个例子没有使用下标,如果需要的话可以按前面提到的方法去获取。

for value in array.dropFirst(5) {  
    // use value here 
}

使用removeFirst()可以返回数组片(slice)第一个元素,然后该元素会从数组片中删除。接下来的代码段结合了removeFirst()和dropFirst(),首先去掉前5个元素,然后遍历数组剩余的元素。

var slice = array.dropFirst(5)  
while !slice.isEmpty {  
    let value = slice.removeFirst()  
    // use value here 
}

另外也有很多方式可以遍历数组,包括在需要的时候才去获取数组切片的值(使用lazy进行延迟加载),但是以上提到的方法已经基本够用了。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读