Suppress Unused Function Result Warnings with @discardableResult in Swift 3
--
Say I have a method declaration like this
open func addEvent(withKey key: EventKey) -> Event {
let event = createEvent()
// do some magic to the event
return event
}
And when I call this method like addEvent(withKey: .appLaunched)
, I immediately get a warning from the compiler, saying Result to call to addEvent(withKey:) is unused
.
This is a fair useful warning to a lot of use cases, however, in my example, while sometimes I do capture the result event, and maybe mutate it even further, at times, I intend to ignore the result.
Swift compiler tries to help by prefixing the function call with _ =
, so it basically assign the result to a wildcard variable.
It works at the beginning, but once there are many method calls, the code becomes quite messy, like
_ = addEvent(withKey: .viewDidLoad)
_ = addEvent(withKey: .viewWillAppear)
_ = addEvent(withKey: .viewDidApear)
_ = addEvent(withKey: .adLoaded)
...
So, a better approach in this case would be applying @discardableResult
attribute to the method declaration, like
@discardableResult open func addEvent(withKey key: EventKey) -> Event {
let event = createEvent()
// do some magic to the event
return event
}
I found sometimes I want to write the attribute at the same line as the function declaration, and sometimes on its own line (especially when I have other attributes, like @available
). But it is not a big deal, if the @discardableResult
attribute is there, then the compiler warning for result not used will just go away.
And don’t worry, in case I want to capture the result, I can still do let event = addEvent(withKey: .viewDidLoad)
, and then mess around with it afterwards. Good news is that the compiler won’t annoy you if you capture the result (of course!)
😄