在for语句中使用String.CharacterView.Index.successor() [英] Using String.CharacterView.Index.successor() in for statements
问题描述
将来, 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
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屋!