Can I have static subscript in Swift?

Since Swift 5.1 static and class subscripts are possible (Proposal SE-0254). They are called type subscripts.

So this can be done now:

struct MyStruct {
    static var values = ["a", "b", "c"]
    static subscript(index: Int) -> String {
        values[index]
    }
}

print(MyStruct[2]) // prints c

Short answer is no. Static is limited to methods and properties within a struct or class. Subscripts are operators and cannot be set to static. This is doable:

struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// prints "six times three is 18"

but you do have to make an object of threeTimesTable (in this case). Additionally this is worth looking at:

http://www.codingexplorer.com/custom-subscripts-swift/

Tags:

Ios

Swift