Swift: Using Map to Deal with Optionals

I’m currently re-reading the Functional Programming in Swift book, and I came across a very interesting way of dealing with optionals that I missed the first time around (when Swift first came out!).

Let’s say you want to increment an optional value. Normally, you would write it like this:

func increment(someNumber: Int?) -> Int? {
    if let number = someNumber {
        return number + 1
    } else {
        return nil
    }
}

increment(5)   // Some 6
increment(nil) // nil

Apparently you can use the map function instead to do the same thing in much fewer lines of code:

func increment(someNumber: Int?) -> Int? {
    return someNumber.map { number in number + 1 }
}

increment(5)   // Some 6
increment(nil) // nil

The map approach also works for other optionals, such as String!

func hello(someName: String?) -> String? {
    return someName.map { name in "Hello, \(name)"}
}

hello("NatashaTheRobot") // Some "Hello, NatashaTheRobot"
hello(nil) // nil

Of course it’s up to you and your team to decide if this approach is readable and when to use it, but it’s good to know it’s an option!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.