Subscripts provide a convenient way to access the elements of a collection, list, or sequence directly by index. Whether you’re dealing with arrays, dictionaries, or custom types, subscripts allow you to set and retrieve values without needing separate methods for each operation.
What is a subscript
?
Subscripts are shortcuts for accessing the member elements of a collection, list, or sequence. They are used to set and retrieve values without needing separate methods for each operation.
Use Case of a subscript
extension Collection {
// Support collection[safe: number]
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
// Support collection[safe: number, default: "some default value"]
subscript (safe index: Index, default value: Element) -> Element {
return indices.contains(index) ? self[index] : value
}
}
let pokemon = ["Pikachu", "Lugia", "Dragonite", "Mewtwo"]
pokemon[10] // will crash 💥
pokemon[safe: 10] // returns nil
pokemon[safe: 10, default: "Pikachu"] // returns Pikachu.
Download the Swift Playground here
Conclusion
Subscripts provide a convenient way to access the elements of a collection, list, or sequence directly by index. Whether you’re dealing with arrays, dictionaries, or custom types, subscripts allow you to set and retrieve values without needing separate methods for each operation.
Resources:
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/subscripts/
Top comments (0)