@discardableResult

@discardableResult

Ignoring non-void function returns so they do not warn on unused results.

ยท

2 min read

Ignoring non-void function returns so they do not warn on unused results.

You are writing your code and have a couple of functions that return some values. But when you are invoking some of these functions you are not using the returning values and are getting warnings like this through your compiler.

warning: result of call to 'someFunction()' is unused

So to avoid these warnings, your code starts looking like this:

let _ = someFunction()

The warning was now suppressed and your console outputs the expected result. But you are feeling not happy about seeing your code with a lot of let _. This can be prone to future errors.

๐Ÿ‘‰๐Ÿฟ You need @discardableResult.

In Swift annotating methods and functions with @discardableResult informs the compiler that a non-void return type should be consumed. So, ignored results do not raise warnings or errors.

warning: result of call to 'someFunction()' is unused

The @discardableResult attribute enables developers to indicate when their functions and methods produce a non-essential result and should not produce a warning.

extension Array { 
    mutating func removeLast() -> Element {
        return remove(at: count - 1)
    }
}

The above function removes the last element of an Array. When we call array.removeLast() from var array = [2, 4, 7, 0], array.removeLast() returns 0.

var array = [2, 4, 7, 0]
array.removeLast()
// warning: result of call to 'removeLast()' is unused
// array.removeLast()
//      ^         ~~
// [2, 4, 7]

As our intention was just to remove the last element of the array and do nothing with the returned value, it makes sense to us to discard this value. So rather suppress the warning message with let _ = array.removeLast(), we should use @discardableResult.

In the following snippet, we expect to be able to discard the return value after invoking array.removeLast().

extension Array { 
    @discardableResult
    mutating func removeLast() -> Element {
        return remove(at: count - 1)
    }
}

When we call array.removeLast() again, we will not see the warning anymore.

var array = [2, 4, 7, 0]
array.removeLast()
// [2, 4, 7]

๐Ÿ™Œ๐Ÿฟ

Did you find this article valuable?

Support Amarildo Codes by becoming a sponsor. Any amount is appreciated!

ย