Using Optional’s map with Void functions

Toby O'Connell
CodeX
Published in
2 min readJan 28, 2021

Many swift developers will know that any function without an explicit return type specified will return Void.

Usually, ignoring the return type produces the following warning:

Ignoring the return type from a function

However, this is not the case for functions returning Void (or we’d have warnings everywhere!) This becomes clear when using the @discardableResult annotation:

Void results can be discarded by default

What this ultimately means is that the following two functions are equivalent:

func doSomething() -> Void {
...
}
func doSomething() {
...
}

Another interesting fact is that Void? also produce no warning. This is necessary for optional chaining as the result of an optionally chained Void function is Void?. If this were not the case then the following would present an error:

let myType: MyType? = MyType()myType?.doSomething()

These properties of Void combine to provide an unusual but handy use of Optional.map(_:). When we inspect the map function, we see the return type is the same as the transform closure’s return type, only wrapped in an Optional.

func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U?

We know that if the transform function returns Void then the map will return Void?, which can be safely ignored without issue. The following code is therefore completely valid and presents no warning:

func doSomething(_ message: String) {
...
}
let message: String? = "Hello, World!"message.map(doSomething)

This saves a few lines over the alternative which would look something like this:

func doSomething(_ message: String) {
...
}
let message: String? = "Hello, World!"if let message = message {
doSomething(value: message)
}

--

--

Toby O'Connell
CodeX
Writer for

Swift / iOS developer - I write about things that I find interesting or innovative.