Subscripts in Swift
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/
Read more
- Hacktoberfest 2024 • 4 minutes reading time.
- SwiftLeeds 2024, Day 2 • 7 minutes reading time.
- A Guide to UI Testing in Swift • 15 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook