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/

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay