NEW: Get your ticket to Hacking with Swift Live 2020! >>

How to ignore return values using @discardableResult

Swift version: 5.1

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 discardableLog(_ 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.

SPONSORED Why the top iOS apps rely on Instabug for crash reporting. Crash reporting + Bug reporting + Customizable in-app surveys all in one SDK. Know which line of code caused the crash along with network logs, repro steps, and the session profiler to identify and resolve severe crashes quickly. See more detailed features comparison and try Instabug for free here.

Listen to the Swift over Coffee podcast

Available from iOS 8.0

Similar solutions…

About the Swift Knowledge Base

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

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5