Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first element of a tuple in an array in Swift [duplicate]

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"

like image 737
ThisISswift Avatar asked Jan 03 '16 04:01

ThisISswift


2 Answers

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)
}
like image 186
Craig Siemens Avatar answered Nov 17 '22 13:11

Craig Siemens


You can access each tuple by element number. let result = [cars[0].0, cars[1].0, cars[2].0]

like image 22
SwiftMatt Avatar answered Nov 17 '22 15:11

SwiftMatt