Home > Software design >  Find closest struct to given struct property in array of structs?
Find closest struct to given struct property in array of structs?

Time:08-11

How can I find the closest struct in an array of structs if given a struct of the same type?

let people = [
    Person(
        name: "Tom",
        height: 104.0
    ),
    Person(
        name: "James",
        height: 80.0
    ),
    Person(
        name: "Sam",
        height: 110.0
    )
]

let jeff = Person(
    name: "Jeff",
    height: 78.0
)

What I want to do is search the people array and find the result that closest matches the height of jeff.

CodePudding user response:

You just need to do a simple for loop through people.


var closest = Person(
    name: "super tall guy",
    height: 999.0
)
var diff:Float = 999

for person in people {
    let currDiff = abs(person.height - jeff.height)
    if (currDiff < diff) {
        closest = person
        diff = currDiff
    }
}

print(closest)

CodePudding user response:

you could try a different approach than using an explicit for loop, such as in this example code.

 struct Person: Identifiable, Codable {
     let id = UUID()
     var name: String
     var height: Double
     
     func compare(to other: Person) -> Double { // <-- here
         abs(height - other.height)
     }
  }
 
    // -- here
    let closest = people.min{$0.compare(to: jeff) < $1.compare(to: jeff)}

    print("\n---> closest: \(closest)")
  • Related