Home > Software design >  How to unwrap tuple with CompactMap in swift 5
How to unwrap tuple with CompactMap in swift 5

Time:12-17

I'm kickbell.

I usually use CompactMap to remove nil.

for example,

let wrappedArray = [nil, 2, 6, "ddf"].compactMap{ $0 }

wrappedArray //[2, 6, "ddf"]

and, i want same result the tuple. but, it not working i expected.

what should i do ?

plz reply when you have time.

thanks for your help.

let tuple: [(Bool?, Int?)] = [
  (state: true, value: 3),
  (state: true, value: nil),
  (state: nil, value: 55),
  (state: false, value: nil)
]

let wrappedTuple = tuple.compactMap{$0}

wrappedTuple
//[(.0 Optional(true), .1 3),
//(.0 Optional(true), nil),
//(nil, .1 55),
//(.0 Optional(false), nil)]

CodePudding user response:

the let wrappedTuple = tuple.compactMap{$0} works if you had (note the last ?):

        let tuple: [(Bool?, Int?)?] = [  // <-- here
          (state: true, value: 3),
          (state: true, value: nil),
          (state: nil, value: 55),
          (state: false, value: nil),
          nil,
          nil
        ]

What you may want (with your original tuple) is to use filter, such as:

 let wrappedTuple = tuple.filter{ $0.0 != nil && $0.1 != nil }

and adjust the logic as you desire.

If you want non-optionals in the tuples as the results, try this:

 let wrappedTuple = tuple.filter{ $0.0 != nil && $0.1 != nil }.map{ ($0.0!,$0.1!) }

You could still use compactMap like this. It really depends on what you want to achieve.

 let wrappedTuple = tuple.compactMap{$0.0}
  • Related