@discardableResult Attribute in Swift

Get rid of that annoying warning

Image for post
Image for post
Photo by dylan nolte on Unsplash

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.

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE) OR Coding in Swift Playgrounds (guide HERE)

Terminology

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

Image for post
Image for post

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,

@discardableResult

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:

Image for post
Image for post

How easy was that?

I’d say too easy.

Now why wasn’t I doing that before??

Conclusion:

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store