字符串迭代

Version < 3.0

let string = "My fantastic string"
var index = string.startIndex

while index != string.endIndex {
    print(string[index])
    index = index.successor()
}

注意:endIndex 是在字符串结尾之后(即 string[string.endIndex] 是一个错误,但 string[string.startIndex] 很好)。另外,在一个空字符串("")中,string.startIndex == string.endIndextrue。一定要检查空字符串,因为你不能在空字符串上调用 startIndex.successor()

Version = 3.0

在 Swift 3 中,String 索引不再包含 successor()predecessor()advancedBy(_:)advancedBy(_:limit:)distanceTo(_:)

相反,这些操作被移动到集合,该集合现在负责递增和递减其索引。

可用的方法是 .index(after:).index(before:).index(_:, offsetBy:)

let string = "My fantastic string"
var currentIndex = string.startIndex

while currentIndex != string.endIndex {
    print(string[currentIndex])
    currentIndex = string.index(after: currentIndex)
}

注意:我们使用 currentIndex 作为变量名称,以避免与 .index 方法混淆。

而且,例如,如果你想走另一条路:

Version < 3.0

var index:String.Index? = string.endIndex.predecessor()

while index != nil {
    print(string[index!])
    if index != string.startIndex {
        index = index.predecessor()
    }
    else {
        index = nil
    }
}

(或者你可以先将字符串反转,但如果你不需要一直浏览字符串,你可能更喜欢这样的方法)

Version = 3.0

var currentIndex: String.Index? = string.index(before: string.endIndex)

while currentIndex != nil {
    print(string[currentIndex!])
    if currentIndex != string.startIndex {
        currentIndex = string.index(before: currentIndex!)
    }
    else {
        currentIndex = nil
    }
}

注意,Index 是一个对象类型,而不是 Int。你无法访问字符串字符,如下所示:

let string = "My string"
string[2] // can't do this
string.characters[2] // and also can't do this

但是你可以获得如下特定索引:

Version < 3.0

index = string.startIndex.advanceBy(2)

Version = 3.0

currentIndex = string.index(string.startIndex, offsetBy: 2)

并且可以像这样倒退:

Version < 3.0

index = string.endIndex.advancedBy(-2)

Version = 3.0

currentIndex = string.index(string.endIndex, offsetBy: -2)

如果你可能超出字符串的范围,或者你想指定限制,则可以使用:

Version < 3.0

index = string.startIndex.advanceBy(20, limit: string.endIndex)

Version = 3.0

currentIndex = string.index(string.startIndex, offsetBy: 20, limitedBy: string.endIndex)

或者,可以只迭代字符串中的字符,但根据上下文,这可能不太有用:

for c in string.characters {
    print(c)
}