将两个不同类型的数组排序为一个 [英] Sort Two Arrays of Different Types into One

查看:91
本文介绍了将两个不同类型的数组排序为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,它们是两个不同的对象,并且都包含一个ID字段.我需要做的是在表视图控制器中按顺序显示它们.它们共享相同的基本信息,大小和ID,除了显示的对象类型外,这些都是唯一显示的数据.当用户选择一个单元格时,它将移至一个新视图,该视图显示该对象的更详细信息.

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.

现在,我在表中有两个部分,一个部分用于TypeA,另一部分用于TypeB.他们对各自列表中的所有项目进行排序,但在制造项目时却无序.看起来像这样:

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

我需要的是将它们全部分类为1个部分,并在选择时仍打开详细视图.

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

想法

我可以将它们全部放入AnyObject字典中,并在查看单个项目时确定它们是否属于一种对象类型或另一种.我觉得这样行得通,但是我该如何正确地对其进行排序?

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?

推荐答案

您可以这样做:

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
}

这篇关于将两个不同类型的数组排序为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆