Member-only story

The @discardableResult Attribute in Swift

Gabriel Theodoropoulos
3 min readMar 19, 2021

--

Swift has several small features as a language, many of them being neglected quite often while they consist of small programming gems. One of them is the @discardableResult attribute that everybody wish they knew from the beginning.

What’s the purpose of @discardableResult? Put in simple words, when used to annotate a method, then the returned value of the method can be ignored when it gets called.

Let’s make that clear through a basic example. Say that we have the following method that stores the text given as first argument to the file name provided as second argument:

func save(text: String, to file: String) -> Bool {
do {
guard let docDirURL =
FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first
else { return false }

let saveURL = docDirURL
.appendingPathComponent(file)
.appendingPathExtension("txt")

try text.write(to: saveURL,
atomically: true,
encoding: .utf8)
return true
}
catch {
return false
}
}

This method does nothing more than simply getting the URL to the documents directory, composing the final URL including the file name and the .txt extension, and…

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

No responses yet