字串迭代

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)
}