搜索struct创建的对象

时间:2016-07-20 18:51:37

标签: swift struct swift-structs

我想搜索struct创建的对象。

我们假设这些是Candy struct。

创建的对象
candies = [
  Candy(category:"Chocolate", name:"Chocolate Bar"),
  Candy(category:"Chocolate", name:"Chocolate Chip"),
  Candy(category:"Chocolate", name:"Dark Chocolate"),
  Candy(category:"Hard", name:"Lollipop"),
  Candy(category:"Hard", name:"Candy Cane"),
  Candy(category:"Hard", name:"Jaw Breaker"),
  Candy(category:"Other", name:"Caramel"),
  Candy(category:"Other", name:"Sour Chew"),
  Candy(category:"Other", name:"Gummi Bear")
]

我们怎样才能找到" Lollipop"元素没有创建两个数组并通过索引查找对象?

2 个答案:

答案 0 :(得分:3)

就是这样:

candies.first { $0.name == "Lollipop" }

如果您希望有多个“Lollipop”,那么:

candies.filter { $0.name == "Lollipop" }

行动中:

 13> struct Candy { 
 14.     let cat: String 
 15.     let name: String 
 16. } 
 17> var candies = [ 
 18.     Candy (cat: "Hard", name: "Lollipop"), 
 19.     Candy (cat: "Hard", name: "Jaw Breaker") 
 20.     ] 
candies: [Candy] = 2 values {
  [0] = {
    cat = "Hard"
    name = "Lollipop"
  }
  [1] = {
    cat = "Hard"
    name = "Jaw Breaker"
  }
}

 21> candies.first { $0.name == "Lollipop" } 
$R1: Candy? = (cat = "Hard", name = "Lollipop")

 22> candies.filter { $0.name == "Lollipop" } 
$R2: [Candy] = 1 value {
  [0] = {
    cat = "Hard"
    name = "Lollipop"
  }
}

答案 1 :(得分:1)

你可以试试这个:

if let found = find(lazy(array).map({ $0.name }), "Foo") {
    let obj = array[found]
}