Swift sorting array of structs by string double

后端 未结 2 570
名媛妹妹
名媛妹妹 2021-01-27 01:56

I have an array of structs that I am looking to sort from highest to lowest based on Double value stored as a String. This is the way I\'m currently doing it:

us         


        
相关标签:
2条回答
  • 2021-01-27 02:04

    You can convert the weekFTC string to a Double and then compare, like so:

    users.sort { (lhs, rhs) -> Bool in
        let lhsVal = Double(lhs.weekFTC) ?? 0
        let rhsVal = Double(rhs.weekFTC) ?? 0
    
        return lhsVal > rhsVal
    }
    

    Comparing strings directly does a lexicographical comparison.

    Example:

    var array = ["111", "e3", "22"]
    
    array.sort { (lhs, rhs) -> Bool in
        return lhs > rhs
    }
    print(array) //["e3", "22", "111"]
    

    So we should see if the string can be made into a number and then sort.
    This time it will do a numeric comparison, like so:

    var array = ["111", "e3", "22"]
    
    array.sort { (lhs, rhs) -> Bool in
        let lhs = Double(lhs) ?? 0
        let rhs = Double(rhs) ?? 0
        return lhs > rhs
    }
    print(array) //["111", "22", "e3"]
    
    0 讨论(0)
  • 2021-01-27 02:24

    Use a comparator which is able to handle numeric strings

    users.sort { $0.weekFTC.compare($1.weekFTC, options: .numeric) == .orderedDescending }
    
    0 讨论(0)
提交回复
热议问题