Sort Two Arrays of Different Types into One

前端 未结 3 1174
粉色の甜心
粉色の甜心 2020-12-18 14:46

I have two arrays, they are of two different objects, and both contain an ID field. What I need to do is display them in order in a table view controller. They share the sam

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 15:28

    You can do this like so:

    class TypeA {
        var ID: Int
    
        init(_ id: Int) {
            self.ID = id
        }
    }
    
    class TypeB {
        var ID: Int
    
        init(_ id: Int) {
            self.ID = id
        }
    }
    
    struct Wrap {
        var ID: Int {
            return a?.ID ?? b?.ID ?? 0
        }
        let a: TypeA?
        let b: TypeB?
    }
    
    var arrayA = [TypeA(1), TypeA(3), TypeA(5)]
    var arrayB = [TypeB(2), TypeB(4)]
    
    let sortedArray = (arrayA.map { Wrap(a: $0, b: nil) } + arrayB.map { Wrap(a: nil, b: $0)})
                          .sorted { $0.ID < $1.ID }
    

    When row is selected you can determine object with:

    if let a = sortedArray[index].a {
        // TypeA row selected
    } else if let b = sortedArray[index].b {
        // TypeB row selected
    }
    

提交回复
热议问题