I tried adding the @discardableResult attribute to a subscript function in my open-source library GitHub - willonboy/ZTChain: ZTChain is a lightweight library designed to facilitate chaining syntax in Swift, making your code more readable and expressive., but it results in an error. Why is this happening, and how can I resolve it?
Perhaps someone with more knowledge than I will drop in and give you a real answer but my guess is because in the context where a subscript is being used as a getter, it would be really strange to have the result be discardable. Why get the value in the first place if you're not going to use it?
As I said though, this is just my guess.
I think you make some valid points, but on the other hand, after all, a subscript is still a “func.” What other non-“init” functions in Swift cannot be decorated with “@discardableResult”?
If you're trying to ignoring the result of a subscript getter then you're using it for a side effect. I think the point is that subscripts probably aren't intended to be used to achieve side effects, but rather to get and set values. This restriction seems likely an indication to the programmer trying to ignore this intent that they're using the wrong mechanism.
Haha, there are indeed ‘side effects’ in my library.
The same applies to "why a property getter cannot be marked @discardableResult".
This is not technically true; subscript
s are much more like var
s than func
s. They're storage declarations; they have accessors and observers, and they can appear as l-values (on the left-hand side of assignment, as inout
parameters to a function, etc.). The major similarity that they have to functions is just that they accept parameters.
I've definitely seen subscripts in the wild where the mere act of reading it is used for its side-effects (hello, swift::ConstraintGraph
), but I don't think requiring the user to explicitly discard the result is onerous in any way; it only makes it more clear what you're intending to do at the call site.
Awesome! I think your explanation is the most reasonable. It truly cleared up the doubts I had. The reason I want to use @discardableResult to decorate the subscript method is because my library is quite special—it constantly calls the subscript method. If users are required to explicitly discard the result all the time, it would obviously be impractical because it happens too often. So, is there any better solution for this?