Sort Two Arrays of Different Types into One

前端 未结 3 1172
粉色の甜心
粉色の甜心 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:13

    Put all common properties into a protocol, the build and sort an array of that common protocol:

    protocol HasID {
        var id: Int { get }
    }
    
    class TypeA : HasID, CustomStringConvertible {
        var id: Int
    
        init(_ id: Int) {
            self.id = id
        }
    
        var description : String {
            return ("TypeA(\(self.id))")
        }
    }
    
    class TypeB : HasID, CustomStringConvertible {
        var id: Int
    
        init(_ id: Int) {
            self.id = id
        }
    
        var description : String {
            return ("TypeB(\(self.id))")
        }
    }
    
    let typeA = [TypeA(1), TypeA(2), TypeA(5), TypeA(6)]
    let typeB = [TypeB(3), TypeB(4), TypeB(7)]
    let result: [HasID] = (typeA + typeB).sorted { $0.id < $1.id }
    
    print(result)
    
    [TypeA(1), TypeA(2), TypeB(3), TypeB(4), TypeA(5), TypeA(6), TypeB(7)] 
    

提交回复
热议问题