myArray = [cat, red ,dog, blue, horse, yellow tiger, green ]
How can I sort this array such that colour is displayed first followed by animals like this:
myArray = [red, blue, yellow, green, cat, dog, horse, tiger]
myArray = [cat, red ,dog, blue, horse, yellow tiger, green ]
How can I sort this array such that colour is displayed first followed by animals like this:
myArray = [red, blue, yellow, green, cat, dog, horse, tiger]
Instead of an String array, you can use array of struct with enum to differentiate your custom type priority, as such:
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
}
Sort array using custom type data:
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 }
Output:
print(data.map{ $0.text })
// ["red", "blue", "yellow", "green", "cat", "dog", "horse", "tiger"]