Swift: Discardable Result

Patrick
Oct 22, 2016

--

Swift 2.2

In Swift 2.2, if you called a function and didn’t use its returned result you would receive no warning. To generate a warning the method definition itself would need to be annotated with:

@warn_unused_result

i.e.

@warn_unused_result func add(a: Int, b: Int) -> Int {
return a + b
}

which produces the following warning when used:

Swift 3 and above

This behaviour has been flipped around in Swift 3 and above where now any unused returned results generate a warning. If you’re designing an API and certain function return values should more so be treated as side effects you can annotate the function with:

@discardableResult

i.e.

@discardableResult 
func add(a: Int, b: Int) -> Int {
return a + b
}

The swift proposal for this change can be read here

--

--