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.
While the most common subscripts are the ones that take a single parameter, subscripts are not limited to single parameters. Subscripts can take any number of input parameters and these parameters can be of any type.
Custom subscripts in Swift allow you to write shortcuts to elements from collections or sequences and can be defined within classes, structures, and enumerations. You can use subscripts to set and retrieve values without exposing the inner details of a certain instance.
In Swift4, subscripts are the shortcuts which are used to access elements of a list, sequence or a collection. Subscript is used to set or retrieve a value using index instead of writing functions. For example: Array[Index], Dictionary[Key]
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With