Sort array by calculated distance in Swift

后端 未结 3 915
南方客
南方客 2020-12-06 02:32

So I have an array of custom objects which have a Double latitude and Double longitude value. I would like to sort the array based on the calculated distance from a specific

3条回答
  •  借酒劲吻你
    2020-12-06 03:30

    Thats quite easy to do. Your function which calculate the distance must take two parameter of type what is in your array you want to sort and return Bool, for example:

    // I assumed your array stores MyLocation
    func mySortFunc(location1: MyLocation, location2: MyLocation) -> Bool {
    
        // do your calculation here and return true or false
    }
    
    var array: [MyLocation] = ...
    array.sortInPlace { (loc1, loc2) -> Bool in
        mySortFunc(loc1, location2: loc1)
    }
    

提交回复
热议问题