简体   繁体   中英

Finding closest value in array of custom objects in swift

Hi I do have array of custom objects in swift, like below

Objects of below class

Class Person {
  let name: String
  let pointsEarned: CGFloat
}

Array is like below


let person1 = Person(“name1”, “5.6”)

let person2 = Person(“name2”, “6.6”)

let person3 = Person(“name3”, “1.6”)

let persons = [person1, person2, person3 ]

I would like find person who's earned points are close to 7.0

Is there extension on array I can write for this?

Appreciate any help. Thanks.

Alexander's answer is good, but you only need the min .

public extension Sequence {
  func min<Comparable: Swift.Comparable>(
    by getComparable: (Element) throws -> Comparable
  ) rethrows -> Element? {
    try self.min {
      try getComparable($0) < getComparable($1)
    }
  }
}

I also think abs as a global function looks archaic. magnitude is the same value.

persons.min { ($0.pointsEarned - 7).magnitude }

You can use the argument label with a trailing closure if you want:

persons.min(by:) { ($0.pointsEarned - 7).magnitude }

Sort your objects by their distance from the goal ( 7 ) , computed as abs(goal - score)`:

people.sort { abs(7 - $0.score) < abs(7 - $1.score) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM