如何在swift中获取数组中元组的第一个元素[重复]

时间:2021-09-25 14:33:45

This question already has an answer here:

这个问题在这里已有答案:

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"

我想得到每个元组中的第一项结果应该是“汽车”,“楼梯”,“表”

2 个解决方案

#1


9  

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

要获得包含第一项的[String],您可以执行此操作

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

#2


1  

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

您可以按元素编号访问每个元组。让结果= [cars [0] .0,cars [1] .0,cars [2] .0]

#1


9  

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

要获得包含第一项的[String],您可以执行此操作

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

#2


1  

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

您可以按元素编号访问每个元组。让结果= [cars [0] .0,cars [1] .0,cars [2] .0]