Subscripts

suggest change

Extensions can add new subscripts to an existing type.

This example gets the character at an integer offset. Swift 2 used advancedBy. An offset past the end traps.

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

Swift 3 and later:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents