I have an array with some tuples inside. How do I get the first item of that tuple inside the array?
let cars = [("cars","cycles"),("stairs","escalator"),("table","chair")]
I want to get the first item in each tuples result should be "cars", "stairs", "table"
To get the first item at a specific index in the array you can use
let i = 1
cars[i].0
To get a [String]
containing the first items you can do this
cars.map { $0.0 }
Edit
You can loop over the elements a couple ways.
let firstItems = cars.map { $0.0 }
for item in firstItems {
print(item)
}
or
for (first, second) in cars {
print(first)
}
You can access each tuple by element number. let result = [cars[0].0, cars[1].0, cars[2].0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With