#83: Custom Subscripts in Swift

Subscripts let your own types use the familiar square-bracket syntax.

struct TimesTable {
    let factor: Int

    subscript(index: Int) -> Int {
        factor * index
    }
}

let table = TimesTable(factor: 3)
table[4] // 12

This can make domain-specific types much nicer to use when indexed access is part of their natural API.

Like methods and properties, subscripts can also be generic and read-only or read-write.


I'm also on Twitter and GitHub.

Subscribe via RSS.