排序不同对象的数组

问题描述 投票:0回答:1
myArray = [cat, red ,dog, blue, horse, yellow tiger, green ]

如何对这个数组进行排序,以便首先显示颜色,然后是这样的动物:

myArray = [red, blue, yellow,  green, cat,  dog, horse, tiger]
swift
1个回答
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"]
© www.soinside.com 2019 - 2024. All rights reserved.