The main argument backing this proposal is to remove duplication of code, which prevents syntax errors, specially when indices are used.
The expression:
property.listOfStuff[0].otherProperty.theBoolean = !property.listOfStuff[0].otherProperty.theBoolean
will be replaced by:
property.listOfStuff[0].otherProperty.theBoolean.toggle()
This is handy, specially for cases where the value can be easily toggled by the user interacting with the user interface (eg. tapping on a button).
However, in many cases we might need to now the new value, to do other related operations. Like this:
property.listOfStuff[0].otherProperty.theBoolean.toggle()
if property.listOfStuff[0].otherProperty.theBoolean {
// Property is ON, do something related
}
As you can see, we completely miss the point of the proposal, which is to remove the duplicate code (specially the case where indices are used).
Having toggle() return the new value, would prevent code duplication:
let isON = property.listOfStuff[0].otherProperty.theBoolean.toggle()
if isON {
// Property is ON, do something related
}
While toggled() sounds like it would be consistent with other methods (like sort() vs sorted()), it would defeat the purpose of the proposal since "past tense" methods return an immutable copy and do not mutate the original value.
@discardableResult allows the method to be mutating, which allows the method to return the new value, while keeping the API naming convention consistent.
Other examples of mutating methods in the standard library that return a discardable result are:
- Array.remove(at:)
- Array.removeFirst()
- Set.update(with:)
- Set.remove(member:)
- etc.
Regards,
Eneko