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/

Sentry blog image

The countdown to March 31 is on.

Make the switch from app center suck less with Sentry.

Read more

Top comments (0)

Billboard image

📊 A side-by-side product comparison between Sentry and Crashlytics

A free guide pointing out the differences between Sentry and Crashlytics, that’s it. See which is best for your mobile crash reporting needs.

See Comparison

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay