Extensions can add new subscripts to an existing type.
This example gets the character inside a String using the given index:
extension String {
subscript(index: Int) -> Character {
let newIndex = startIndex.advancedBy(index)
return self[newIndex]
}
}
var myString = "StackOverFlow"
print(myString[2]) // a
print(myString[3]) // c
extension String {
subscript(offset: Int) -> Character {
let newIndex = self.index(self.startIndex, offsetBy: offset)
return self[newIndex]
}
}
var myString = "StackOverFlow"
print(myString[2]) // a
print(myString[3]) // c