Swift how to sort array of custom objects by property value

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

    If you are going to be sorting this array in more than one place, it may make sense to make your array type Comparable.

    class MyImageType: Comparable, Printable {
        var fileID: Int
    
        // For Printable
        var description: String {
            get {
                return "ID: \(fileID)"
            }
        }
    
        init(fileID: Int) {
            self.fileID = fileID
        }
    }
    
    // For Comparable
    func <(left: MyImageType, right: MyImageType) -> Bool {
        return left.fileID < right.fileID
    }
    
    // For Comparable
    func ==(left: MyImageType, right: MyImageType) -> Bool {
        return left.fileID == right.fileID
    }
    
    let one = MyImageType(fileID: 1)
    let two = MyImageType(fileID: 2)
    let twoA = MyImageType(fileID: 2)
    let three = MyImageType(fileID: 3)
    
    let a1 = [one, three, two]
    
    // return a sorted array
    println(sorted(a1)) // "[ID: 1, ID: 2, ID: 3]"
    
    var a2 = [two, one, twoA, three]
    
    // sort the array 'in place'
    sort(&a2)
    println(a2) // "[ID: 1, ID: 2, ID: 2, ID: 3]"
    

提交回复
热议问题