0

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.

6
  • 1
    Distance from 7 is just abs(7 - pointsEarned), so sort the objects by whichever has the lowest distence Commented Apr 19, 2020 at 1:40
  • Can you please provide code snippet? I am missing something Commented Apr 19, 2020 at 2:02
  • 3
    people.sort { abs(7 - $0.score) < abs(7 - $1.score) } Commented Apr 19, 2020 at 2:22
  • Thanks! It’s working Commented Apr 19, 2020 at 14:53
  • You are using sort, and then it's people.sort{ insideClosure }.first while it could just be people.min(by: { insideClosure } Commented Apr 19, 2020 at 16:24

2 Answers 2

1

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

people.sort { abs(7 - $0.score) < abs(7 - $1.score) }
Sign up to request clarification or add additional context in comments.

Comments

1

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 }

1 Comment

Woah, didn't know about magnitude. That's so much better!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.