在for语句中使用String.CharacterView.Index.successor() [英] Using String.CharacterView.Index.successor() in for statements

查看:93
本文介绍了在for语句中使用String.CharacterView.Index.successor()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将来, C风格for语句将从Swift中删除.尽管有许多其他的方法可以使用C风格的语句,例如使用stride..<运算符,但这些方法仅在某些条件下有效

In the future, C-style for statements will be removed from Swift. While there are many alternate methods to using the C-style for statements, such as using stride, or the ..< operator, these only work in some conditions

例如,在较早版本的swift中,可以遍历其他所有索引,即

For example, in older versions of swift, it was possible to loop through every other one of the indexes, String.CharacterView.Index, of a String using C-style for statements

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

但是现在不建议使用.有一种方法可以使用while循环

Yet this is now deprecated. There is a way to do the same thing, using a while loop

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

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

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

but it isn't much more than a workaround. There is the ..< operator, which would be perfect for looping through every index of the string

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

但是,这对循环遍历字符串的每个 other 索引或字符串的第n个索引没有帮助

Yet this doesn't help with looping through every other index of the string, or every nth index of the string

除了while循环以外,还有其他快速"方式遍历String的每个其他索引吗?这个问题不仅与字符串索引有关,而且还与具有.successor()之类功能的对象有关,其中stride..<不起作用.

Is there any more "swifty" way of looping through every other index of a String other than a while loop? This question doesn't just pertain to string indexes, but just objects that have functions such as .successor() in general, where stride and ..< don't work.

推荐答案

您可以使用步进"

let str = "abcdefgh"
for i in str.characters.indices where str.startIndex.distanceTo(i) % 2 == 0 {
    print(i,str.characters[i])
}

打印

0 a
2 c
4 e
6 g

根据Sulthan的笔记进行更新

UPDATE, based on Sulthan's notes

for (i,v) in str.characters.enumerate() where i % 2 == 0 {
    print(i, v)
}

这篇关于在for语句中使用String.CharacterView.Index.successor()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆