Mr. Smith
Mr. Smith

Reputation: 4516

Can a Swift subscript return a variable?

In C#, the only indexer that actually returns a variable1,2 are array indexers.

void Make42(ref int x) {x=42;}
void SetArray(int[] array){
    Make42(ref array[0]);} //works as intended; array[0] becomes 42
void SetList(List<int> list){
    Make42(ref list[0]);} //does not work as intended, list[0] stays 0

In the example above, array[0] is a variable, but list[0] is not. This is the culprit behind many developers, writing high-performance libraries, being forced to write their own List implementations (that, unlike the built-in List, expose the underlying array) to get benchmark worthy performance out of the language.

In Swift, ref is called inout and indexer seems to be called subscript. I'm wondering if there's any mechanisms in Swift's subscript to explicitly return a variable rather than a value (a value can be a value-type or reference-type).

Upvotes: 1

Views: 464

Answers (1)

zneak
zneak

Reputation: 138171

If I may bring in C++ parlance, you'd be looking to return a reference to a value. I'm using the term here because it's generally better understood by the programming crowd.

The reason C# limits it to just arrays is that returning arbitrary references may compromise the language's safety guarantees if not done properly.

There appears to be no syntax to return a reference in Swift. Since returning references is hard to verify, and since Swift is rather new and since it aims at being a safe language, it is understandable that Apple didn't go this way.

If you get to a level where you need this kind of performance, you may want to consider C++, in which you can sacrifice almost all the safety you want to get performance.

Upvotes: 2

Related Questions