Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

ios - Sort Two Arrays of Different Types into One

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 same basic info, Size and ID, and those are the only pieces of data displayed, in addition to the type of object it is. When the user selects a cell then it moves to a new view that displays the finer details of the object.

Right now, I have two sections in the table, one for TypeA, and the other for TypeB. They sort through all of the items in their respective list, but are out of order for when the item was made. So it looks like:

TypeA
  ID 1
  ID 2
  ID 5
  ID 6
TypeB
  ID 3
  ID 4
  ID 7

What I need is for it to sort them all into 1 section, and still open the detail view when selected.

Thoughts

I could put them all into an AnyObject dictionary and when looking at individual items determine if they are of one object type or the other. I feel like that would work, but how would I go about sorting that correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)] 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...