1

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).

Community
  • 1
  • 1
Mr. Smith
  • 4,288
  • 7
  • 40
  • 82
  • Can you name any good reason why the code you hinted at should be something one might need? – Mithrandir Jun 03 '14 at 23:15
  • 2
    @Mithrandir, languages exist to satisfy much more than any specific person's needs. Subscript references could be about just as useful as variable references. – zneak Jun 04 '14 at 00:17

1 Answers1

2

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.

Community
  • 1
  • 1
zneak
  • 134,922
  • 42
  • 253
  • 328