Swift how to sort array of custom objects by property value

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

    Nearly everyone gives how directly, let me show the evolvement:

    you can use the instance methods of Array:

    // general form of closure
    images.sortInPlace({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
    
    // types of closure's parameters and return value can be inferred by Swift, so they are omitted along with the return arrow (->)
    images.sortInPlace({ image1, image2 in return image1.fileID > image2.fileID })
    
    // Single-expression closures can implicitly return the result of their single expression by omitting the "return" keyword
    images.sortInPlace({ image1, image2 in image1.fileID > image2.fileID })
    
    // closure's argument list along with "in" keyword can be omitted, $0, $1, $2, and so on are used to refer the closure's first, second, third arguments and so on
    images.sortInPlace({ $0.fileID > $1.fileID })
    
    // the simplification of the closure is the same
    images = images.sort({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
    images = images.sort({ image1, image2 in return image1.fileID > image2.fileID })
    images = images.sort({ image1, image2 in image1.fileID > image2.fileID })
    images = images.sort({ $0.fileID > $1.fileID })
    

    For elaborate explanation about the working principle of sort, see The Sorted Function.

提交回复
热议问题