Swift how to sort array of custom objects by property value

前端 未结 18 2176
逝去的感伤
逝去的感伤 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:46

    [Updated for Swift 3 with sort(by:)] This, exploiting a trailing closure:

    images.sorted { $0.fileID < $1.fileID }
    

    where you use < or > depending on ASC or DESC, respectively. If you want to modify the images array, then use the following:

    images.sort { $0.fileID < $1.fileID }
    

    If you are going to do this repeatedly and prefer to define a function, one way is:

    func sorterForFileIDASC(this:imageFile, that:imageFile) -> Bool {
      return this.fileID > that.fileID
    }
    

    and then use as:

    images.sort(by: sorterForFileIDASC)
    

提交回复
热议问题