-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
There are cases where subscripts provided by Swift standard library types don’t offer specific functionally that we need. Rahter than creating a new type we could extend the existing type adding a subscript that meets our needs. This can be particularly useful when we need to elements in a way the original type doesn’t support. A good example of this is the String type in Swift where we could extend it to provide access to the individual characters within the String. The following code show how we could do this with a subscript.
extension String {
subscript(index: Int) -> Character? {
guard index >= 0 && index < self.count else {
return nil
}
return self[self.index(self.startIndex, offsetBy: index)]
}
}
This extension adds a subscript to the Swift String type that would return the character at the index provided with the subscript. If the index is out of bounds, it would return...