Swift how to sort array of custom objects by property value

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

    Swift 4.0, 4.1 & 4.2 First, I created mutable array of type imageFile() as shown below

    var arr = [imageFile]()
    

    Create mutable object image of type imageFile() and assign value to properties as shown below

       var image = imageFile()
       image.fileId = 14
       image.fileName = "A"
    

    Now, append this object to array arr

        arr.append(image)
    

    Now, assign the different properties to same mutable object i.e image

       image = imageFile()
       image.fileId = 13
       image.fileName = "B"
    

    Now, again append image object to array arr

        arr.append(image)
    

    Now, we will apply Ascending order on fileId property in array arr objects. Use < symbol for Ascending order

     arr = arr.sorted(by: {$0.fileId < $1.fileId}) // arr has all objects in Ascending order
     print("sorted array is",arr[0].fileId)// sorted array is 13
     print("sorted array is",arr[1].fileId)//sorted array is 14
    

    Now, we will apply Descending order on on fileId property in array arr objects. Use > symbol for Descending order

     arr = arr.sorted(by: {$0.fileId > $1.fileId}) // arr has all objects in Descending order
     print("Unsorted array is",arr[0].fileId)// Unsorted array is 14
     print("Unsorted array is",arr[1].fileId)// Unsorted array is 13
    

    In Swift 4.1. & 4.2 For sorted order use

    let sortedArr = arr.sorted { (id1, id2) -> Bool in
      return id1.fileId < id2.fileId // Use > for Descending order
    }
    

提交回复
热议问题