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).

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.