ios - 在 for 语句中使用 String.CharacterView.Index.successor()

标签 ios swift swift2

将来,C-style for statements will be removed from Swift .虽然有许多替代方法可以使用 C 风格的 for 语句,例如使用 stride ,或 ..<运算符,这些仅在某些条件下有效

例如,在旧版本的 swift 中,可以循环遍历所有其他索引, String.CharacterView.Index , 使用 C 风格 for 语句的字符串

for var index = string.startIndex; index < string.endIndex; index = string.successor().successor(){
    //code
}

然而,这现在已被弃用。有一种方法可以做同样的事情,使用 while循环

var index = string.startIndex
while index < string.endIndex{
    //code

    index = index.successor().successor()
}

但这只不过是一种解决方法。有 ..<运算符,非常适合循环遍历字符串的每个索引

for index in string.startIndex..<string.endIndex

然而,这无助于循环遍历字符串的每个 other 索引,或字符串的每个第 n 个索引

除了 while 之外,是否还有更“快速”的方法来遍历字符串的所有其他索引?环形?这个问题不仅与字符串索引有关,还与具有 .successor() 等功能的对象有关。一般来说,哪里 stride..<不工作。

最佳答案

让我们用函数式编程来实现:

let text = "abcdefgh"

text.characters
    .enumerate()  // let's get integer index for every character
    .filter { (index, element) in index % 2 == 0 }  // let's filter out every second character
    .forEach { print($0, $1) } // print

结果:

0 a
2 c
4 e
6 g

关于ios - 在 for 语句中使用 String.CharacterView.Index.successor(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36194060/

相关文章:

ios - 在 iOS 应用程序中,如何让 2 个元素并排放置?

ios - 解析加载图像到 UIImageView iOS

ios - 如何在 swift 5.1 中设置 UICollectionView 的标题大小?

Ios Swift 覆盖 UItextField 的双击

ios - 根据位置删除图像的ScrollView

ios - 应用程序未声明正确的 UIBackgroundMode

ios - 自定义UISlider拇指图标: How to stop thumb icon from reverting back to default circle icon when drag?

swift - 单个 Collection View 的不同单元格外观

swift - 获取 Swift 运行时错误 (NSException)

ios - 自定义 UICollectionViewFlowLayout 边框