Can I have a static index in Swift?

The title pretty much explains the question, I would like to do something like this: MyStruct[123] without having to call a function ( MyStruct.doSomething(123) ) or instantiate ( MyStruct()[123] ). He would have been good at classes or structures.

+5
source share
1 answer

The short answer is no. Static is limited to methods and properties within a structure or class. Subscribers 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 need to make an object out of threeTimesTable (in this case). Also, it's worth a look at:

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

+6
source

Source: https://habr.com/ru/post/1243776/


All Articles