Search code examples
arraysswiftfunctional-programmingoption-type

How to join array of optional integers to string?


Given [Int?], need to build string from it.

This code snippet works

    let optionalInt1: Int? = 1
    let optionalInt2: Int? = nil

    let unwrappedStrings = [optionalInt1, optionalInt2].flatMap({ $0 }).map({ String($0) })
    let string = unwrappedStrings.joined(separator: ",")

But I don't like flatMap followed by map. Is there any better solution?


Solution

  • Here's another approach:

    [optionalInt1, optionalInt2].flatMap { $0 == nil ? nil : String($0!) }
    

    Edit: You probably shouldn't do this. These approaches are better, to avoid the !

    [optionalInt1, optionalInt2].flatMap {
        guard let num = $0 else { return nil }
        return String(num)
    }
    

    or:

    [optionalInt1, optionalInt2].flatMap { $0.map(String.init) }