String Iteration
suggest changeSwift 2:
let string = "My fantastic string"
var index = string.startIndex
while index != string.endIndex {
print(string[index])
index = index.successor()
}
endIndex is the position after the last character. string[string.endIndex] is an error. string[string.startIndex] is valid when the string is not empty. For "", startIndex == endIndex, and moving an index from there traps.
In Swift 3, String indexes no longer have successor(), predecessor(), advancedBy(_:), advancedBy(_:limit:), or distanceTo(_:).
Instead, those operations are moved to the collection, which is now responsible for incrementing and decrementing its indices.
Available methods are .index(after:), .index(before:) and .index(_:, offsetBy:).
let string = "My fantastic string"
var currentIndex = string.startIndex
while currentIndex != string.endIndex {
print(string[currentIndex])
currentIndex = string.index(after: currentIndex)
}
currentIndex is the variable name so it is not confused with the index method.
And, for example, if you want to go the other way (Swift 2):
var index: String.Index? = string.endIndex.predecessor()
while index != nil {
print(string[index!])
if index != string.startIndex {
index = index!.predecessor()
}
else {
index = nil
}
}
(Or you could just reverse the string first, but if you don’t need to go all the way through the string you probably would prefer a method like this)
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 is its own type, not an Int. You cannot subscript a string with an integer:
let string = "My string"
string[2] // can't do this
string.characters[2] // and also can't do this
But you can get a specific index as follows:
Swift 2 used advancedBy:
index = string.startIndex.advancedBy(2)
Swift 3 and later:
currentIndex = string.index(string.startIndex, offsetBy: 2)
And can go backwards like this:
index = string.endIndex.advancedBy(-2)
currentIndex = string.index(string.endIndex, offsetBy: -2)
If you might exceed the string’s bounds, or you want to specify a limit you can use:
Swift 2. The limit argument stopped the index at endIndex instead of trapping:
index = string.startIndex.advancedBy(20, limit: string.endIndex)
Swift 3 and later. limitedBy: makes the result optional:
currentIndex = string.index(string.startIndex, offsetBy: 20, limitedBy: string.endIndex)
Alternatively one can just iterate through the characters in a string, but this might be less useful depending on the context:
for c in string { // Swift 3: for c in string.characters
print(c)
}