Swift version: 5.6
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.now): \(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.now): \(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.
BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.