使用Swift中的变量过滤结果到数组中

时间:2019-05-11 19:03:48

标签: arrays swift if-statement

我有一个汽车制造商和模型的集合,我想知道是否有一种方法可以使用变量作为条件仅返回属于某些制造商的模型?谢谢。

我尝试使用if语句,但是也许还有另一种方法可以完成此操作?

struct Section {

 var make: String
 var model: String!

}

var Cars = [
 Section(make: "BMW", model: ["A", "B", "C"]),
 Section(make: "Ford", model: ["D", "E", "F"]),
 Section(make: "Audi", model: ["G", "H", "I"])
]

var carMake = "BMW"

// aiming to print the models where make = carMake
// for example if carMake = "BMW" the print results would show "A", "B", "C"

1 个答案:

答案 0 :(得分:-1)

struct Section {

  var make: String
  var models: [String]

}
var cars = [
  Section(make: "BMW", models: ["A", "B", "C"]),
  Section(make: "Ford", models: ["D", "E", "F"]),
  Section(make: "Audi", models: ["G", "H", "I"])
]

var carMake = "BMW"

let carMaker = cars.first { (item) -> Bool in
  return item.make == carMake
}

if let carMaker = carMaker {
  print(carMaker.models)
} else {
  print("maker not found")
}