2

I have an array of tuples where the tuple contains some optional values:

let arrayOfTuples: [(Int, String?, String?)] = ...

How can I best remove from the array those tuples where the second element of the tuple is nil (no matter if the 3rd element is nil)?

When I use flatMap like

let flatTuplesArray: [(Int, String, String)] = arrayOfTuples.flatMap({ ($0, $1, $2) }) then a tuple does not appear in the resulting flatTuplesArray if the second or third element of the tuple is nil.

I want to apply flatMap only on the first two elements of the tuple ($0 and $1) but the result array should still have tuples with three elements (and contain "" for $2 nil values).

Super Geroy
  • 123
  • 1
  • 10

2 Answers2

4

You can use Optional.map on the second tuple element to either unwrap it or have it removed (by the outer flatMap), and the nil-coalescing ?? on the third tuple element to replace nil by an empty string:

let arrayOfTuples: [(Int, String?, String?)] = [(1, "a", "b"), (2, nil, "c"), (3, "d", nil)]

let flatTuplesArray = arrayOfTuples.flatMap {
    t in t.1.map { (t.0, $0, t.2 ?? "") }
}

print(flatTuplesArray)
// [(1, "a", "b"), (3, "d", "")]

If t.1 is nil then t.1.map {...} evaluates to nil and is ignored by flatMap. Otherwise t.1.map {...} evaluates to the value of the closure, with $0 being the unwrapped second tuple element.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

Probably, filter can help you:

let arrayOfTuples: [(Int, String?, String?)] = [(1, nil, nil), (2, "", nil)]
let result = arrayOfTuples.filter({ $0.1 != nil })
print(result) // [(2, Optional(""), nil)]
pacification
  • 5,838
  • 4
  • 29
  • 51