Swift how to sort array of custom objects by property value

前端 未结 18 2342
逝去的感伤
逝去的感伤 2020-11-22 02:12

lets say we have a custom class named imageFile and this class contains two properties.

class imageFile  {
    var fileName = String()
    var fileID = Int(         


        
18条回答
  •  执念已碎
    2020-11-22 02:52

    If you are not using custom objects, but value types instead that implements Comparable protocol (Int, String etc..) you can simply do this:

    myArray.sort(>) //sort descending order
    

    An example:

    struct MyStruct: Comparable {
        var name = "Untitled"
    }
    
    func <(lhs: MyStruct, rhs: MyStruct) -> Bool {
        return lhs.name < rhs.name
    }
    // Implementation of == required by Equatable
    func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
        return lhs.name == rhs.name
    }
    
    let value1 = MyStruct()
    var value2 = MyStruct()
    
    value2.name = "A New Name"
    
    var anArray:[MyStruct] = []
    anArray.append(value1)
    anArray.append(value2)
    
    anArray.sort(>) // This will sort the array in descending order
    

提交回复
热议问题