Swift’s @discardableResult

When we’re writing Swift code we might have a function that returns a value as part of its invocation. For example, maybe we’ve a function which sends some data to a server and then returns a boolean to denote success or failure, here’s a mock up

func serviceCall() -> Bool {
    // do something real here
    true
}

We call this method but maybe we don't care what the result is, so we simply call it like this

[code]
serviceCall()

If we build this, swift will report warning: result of call to ‘serviceCall()’ is unused serviceCall(). We can get around this using a discard, for example

let _ = serviceCall()
// OR
_ = serviceCall()

but there’s another way to tell the compiler to ignore this warning. We mark the function with the @discardableResult attribute, i.e.

@discardableResult
func serviceCall() -> Bool {
    // do something real here
    true
}

Admittedly this seems a little odd, that the function being called should say, “hey you can just ignore the result”. This is something that should probably be used with care, although if it’s known that the function’s result is likely to be ignored, then it’s better than having lots of discards all over the place to ignore the result of the function.