NEW! Master Swift design patterns with my latest book! >>

How to ignore return values using @discardableResult

Paul Hudson       @twostraws

Many functions return values, but sometimes you don’t care what the return value is – you might want to ignore it sometimes, and use it other times.

As an example, Swift’s dictionaries have an updateValue() method that lets you change the value for a given key. If the key was found you’ll be sent back the previous value, but if the key wasn’t found you’ll get back nil. This makes it a nice way to update and check at the same time, if you need it:

var scores = ["Sophie": 5, "James": 2]
scores.updateValue(3, forKey: "James")

That code will return 2, because it was the previous score for James:

The updateValue() method is marked with @discardableResult because it’s the kind of thing you might want to use for a while then stop using, or vice versa. Without that attribute in place you’d need to assign the result to underscore to silence the warning, like this:

_ = scores.updateValue(3, forKey: "James")

You can use @discardableResult in your own functions. For example, you might write a logging function that accepts a string and optionally also a log level. This function will internally assemble a complete log line out of the message, log level, and current date, but it will also return that log message in case it needs to be used elsewhere.

In code it would look something like this:

enum LogLevel: String {
    case trace, debug, info, warn, error, fatal
}

func log(_ message: String, level: LogLevel = .info) -> String {
    let logLine = "[\(level)] \(Date()): \(message)"
    print(logLine)
    return logLine
}

log("Hello, world!")

Although the result from log() is interesting and might be useful sometimes, most of the time users aren’t going to care so this is a sensible place to use @discardableResult:

@discardableResult func log(_ message: String, level: LogLevel = .info) -> String {
    let logLine = "[\(level)] \(Date()): \(message)"
    print(logLine)
    return logLine
}

If you expect folks to use the result most or nearly all of the time, it’s probably better to leave off @discardableResult and make them use _ to silence the warning instead.

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Learn Swift faster!

Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>