@discardableResult Attribute in Swift
Get rid of that annoying warning
Difficulty: Beginner | Easy | Normal | Challenging
It’s one of those things. Swift gives you a warning and you can change a piece of code to suppress the warning.
You change it, and life goes on.
Then you discover that an attribute can help you out.
That’s a bingo.
attribute: A way of providing information about a declaration of type
The case for the @discardableResult
In my Medium post about securing data in the keychain I had a rather nice function that returns the OSStatus after the save operation is complete.
Here is the function signature:
func save(key: String, data: Data) -> OSStatus
So to save a piece of data I decided that I wasn’t interested in the result of the function. This is because if I don’t Swift generates a warning that the variable is not used
The warning in full? Initialization of immutable value ‘status’ was never used; consider replacing with assignment to ‘_’ or removing it
So as a solution to remove this I use the underscore in Swift.
_ = kc.save(key: "MyString", data: data)
Is this an issue?
Not really, and it removes any warning. Nice. But there is another way around this. A better way,
In the function (and notably not in any associated protocol) the
attribute is added. To make this a little clearer I’ll use a gist for the modified function
Which we can then call, but crucially we can (well) discard the result.
this means we can call with
No errors: just an easy life.
Oh, and the change to my actual code? See the following animated gif:
How easy was that?
I’d say too easy.
Now why wasn’t I doing that before??
If you are creating a public API where the result isn’t likely to be used (at least most of the time), the
attribute @discardableResult gives a great way to avoid having your client use _ to silence that annoying warning.
It doesn’t cost anything, and makes your code easier to read.
Of course, if you expect the client to use the result, please don’t just whack @discardableResult in there anyway.
We always code with our thinking cap on, said someone who misquotes Edward De Bono. So that won’t be a problem, and @discardableResult is a great
attribute to have in our coding armoury.
Extend your knowledge
- Apple have documentation about attributes HERE
The Twitter contact:
Any questions? You can get in touch with me HERE