Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have static subscript in Swift?

Tags:

ios

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.

like image 391
gfpacheco Avatar asked Feb 24 '16 17:02

gfpacheco


People also ask

What is multidimensional subscript in Swift?

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.

What is subscript in Swift stack overflow?

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.

What is subscript give example of use IOS?

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]


2 Answers

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
like image 82
Falkone Avatar answered Oct 13 '22 22:10

Falkone


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/

like image 35
Kyle Amonson Avatar answered Oct 13 '22 20:10

Kyle Amonson