排序不同对象的数组

时间:2018-03-06 09:29:09

标签: swift

myArray = [cat, red ,dog, blue, horse, yellow tiger, green ]

如何对此数组进行排序,以便首先显示颜色,然后显示以下动物:

myArray = [red, blue, yellow,  green, cat,  dog, horse, tiger]

1 个答案:

答案 0 :(得分:2)

您可以使用带有枚举的struct数组来代替String数组,以区分您的自定义类型优先级,如下所示:

enum MyType: Int {
    case color, animal // Prioritize your custom type here, in this example color comes first, than animal
}

struct MyData {
    let type: MyType
    let text: String
}

使用自定义类型数据对数组进行排序:

var array: [MyData] = [
    MyData(type: .animal, text: "cat"),
    MyData(type: .color, text: "red"),
    MyData(type: .animal, text: "dog"),
    MyData(type: .color, text: "blue"),
    MyData(type: .animal, text: "horse"),
    MyData(type: .color, text: "yellow"),
    MyData(type: .animal, text: "tiger"),
    MyData(type: .color, text: "green"),
]
array.sort { $0.type.rawValue < $1.type.rawValue }

输出:

print(data.map{ $0.text })
// ["red", "blue", "yellow", "green", "cat", "dog", "horse", "tiger"]