DEV Community

Wesley de Groot
Wesley de Groot

Posted on • Originally published at wesleydegroot.nl on

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.
Enter fullscreen mode Exit fullscreen mode

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/

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)