Every value in a Swift string has a property called its Index
which corresponds to its position. However, because Strings are composed of unicode scalars, and the number of unicode scalars which compose an individual Character
can vary, one cannot index Strings using Integers.
As a result there are three properties and two methods for indexing strings. They are:
startIndex
- This is a property of a String that shows where the first character is.endIndex
- The position after the last character of the string. As a result, it isn't a valid property for a String's substringindices
- For accessing all the indices in a String.index(before:)
,index(after:)
andindex(_:offsetBy:)
are methods to access the indices before or after a specific index.
Example uses of the above methods:
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a
for index in greeting.indices {
print("\(greeting[index]) ", terminator: "")
}
// Prints "G u t e n T a g ! "
As with arrays, one cannot access indices outside the bounds of the String:
greeting[greeting.endIndex] // Error
greeting.index(after: greeting.endIndex) // Error
To insert a single character into a string at a specified index, use the insert(_:at:)
method.
To insert the contents of another string at a specified index, use the insert(contentsOf:at:)
method.
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"
Similarly, to remove a single character use the remove(at:)
method, and to remove a substring at a specified range use the removeSubrange(_:)
method.
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"