@discardableResult - know if the result is indeed discarded

@discardableResult func doSomething() -> Bool {
    // does something
    return true
}

This function can be called in the following ways:

doSomething()
let didSucceed = doSomething()

Is there a way to differentiate the two from inside the doSomething() function, as in, is there a way to know if the caller is using the result?

Answered by DTS Engineer in 794318022
is there a way to know if the caller is using the result?

Not really.

Certainly, there’s no way to distinguish those cases for standard types, like Bool. For more complex types you could do something ‘clever’. For example, you might return a class and require the client to call a method on that class to tell you that they used it. However, this seems kinda weird, and my general advice is that you either not use @discardableResult or design your interface such that this distinction isn’t important.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer
is there a way to know if the caller is using the result?

Not really.

Certainly, there’s no way to distinguish those cases for standard types, like Bool. For more complex types you could do something ‘clever’. For example, you might return a class and require the client to call a method on that class to tell you that they used it. However, this seems kinda weird, and my general advice is that you either not use @discardableResult or design your interface such that this distinction isn’t important.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

@discardableResult - know if the result is indeed discarded
 
 
Q