Reputation: 143
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.
Upvotes: 0
Views: 315
Reputation:
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 }
Upvotes: 1
Reputation: 63321
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) }
Upvotes: 1