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 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • This is a great post! Isn’t map lovely?

    I think it’s at its best when you combine it with the ?? operator to return some default value instead of an optional. For example, hello() can use this to return another string if its parameter is nil:

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

    hello("NatashaTheRobot") // "Hello, NatashaTheRobot"
    hello(nil) "Hello world!"

    Note that the return type is String instead of String? now—you can use this any time you have a default you want to substitute for nil. Pretty handy!

  • Konstantin Koval

    Really Great and Simple!

  • Mike P

    I find

    return someNumber == nil ? nil : someNumber! + 1

    easier to read.

    • Veight Zhou

      In some case, you are right. However, if we want to edit the value if it exists, map become easier.^-^

  • Natasha — great blog! Not to spam you or anything, but since you liked my Railway Oriented Programming talk, I thought you might also find my talk on functional design patterns useful.

    I talk about option maps on slide 132 starting here: http://www.slideshare.net/ScottWlaschin/fp-patterns-ndc-london2014/132

    I’d welcome feedback. Cheers!

  • Witold

    Hi, just wanted to note that the easiest way to increment an optional would be:

    Second example works better – great way to keep the code more succint 🙂