Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift get vs _read

What's the difference between the following 2 subscripts?

subscript(position: Int) {
    get { ... }
}
subscript(position: Int) {
    _read { ... }
}
like image 798
Wowbagger and his liquid lunch Avatar asked Feb 07 '20 00:02

Wowbagger and his liquid lunch


1 Answers

_read is part of the Swift Ownership story that has been in development for a while now. Since read (the likely name once it goes through Swift Evolution) is fairly advanced concept of the language you will probably want to read at least where it is described in the Ownership Manifesto here to get a more full answer than I'll provide here.

It is an alternative to get on subscripts that allows you to yield a value instead of return a value. This is essential for move only types because they cannot be copied (that is their entire purpose) which is what happens when you return a value. By using read it makes it so you could have for example have an Array of move only types and still use the values in it without taking the ownership of them by moving them. The easiest (and not technically correct since it is a coroutine) way to conceptually think about it is that you get a pointer to the object that read yields.

The sibling of read is modify which is currently in the pitch phase of Swift Evolution here so that can also give you some helpful insight into what read is since it is a coroutine as well.

So for now if Xcode gives you a _read to implement simply change it to get since it is a bug since it isn't an official part of the language yet.

like image 170
bscothern Avatar answered Nov 05 '22 16:11

bscothern