2

I want to search objects created by struct.

Let's assume that these are our objects created by 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")
]

How can we find category of "Lollipop" element without creating two arrays and finding the object by their indexes?

do it better
  • 4,627
  • 6
  • 25
  • 41

1 Answers1

3

Just this:

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

If you expect there to be more than one "Lollipop" then:

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

In action:

 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"
  }
}
GoZoner
  • 67,920
  • 20
  • 95
  • 145
  • 2
    Your `candies.first { $0.name == "Lollipop" }` is very cool. But I'm afraid it's for Swift 3 only: in Swift 2 `.first` is only a property for the first object in the array, there's no method accepting a predicate like this. Worth mentioning, IMO. – Eric Aya Jul 20 '16 at 19:12