'Can I have static subscript in Swift?
The title pretty much explains the question, I would like to do something like this: MyStruct[123] without the need to call a function (MyStruct.doSomething(123)) or create an instance (MyStruct()[123]). Having it on classes or structs would be ok.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Falkone |
