テッド
テッド

Reputation: 906

Map Tuples to Array Swift

I have an array of tuples:

[(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)]

What is the best way to convert this to just a single array of [0, 1, 0, 1.....] ?

I have tried

let newArray = tupleArray.map{$0.0, $0.1}

but it doesn't work and says consecutive statements must be separated by ;. There must be some clever way to reduce them.

Upvotes: 1

Views: 1251

Answers (3)

Tushar Moradiya
Tushar Moradiya

Reputation: 2128

This will be your answer :

let arrTouple = [(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)] 
let arr = arrTouple.flatMap{ [$0, $1] }

print(arr) // [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

Upvotes: 1

PGDev
PGDev

Reputation: 24341

Simply use map(_:) and flatMap(_:) to flatten the tuples array,

let tuples = [(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)]
let arr = tuples.map({ [$0.0, $0.1] }).flatMap({ $0 })

Output:

[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54706

You need to add both elements to an array in the closure and you also need to use flatMap instead of map to flatten out the nested array that map would produce.

let arrayOfTuples = [(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)]
let flattenedArray = arrayOfTuples.flatMap{ [$0.0, $0.1] }

Upvotes: 2

Related Questions