0
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]
2
  • 1
    Just sort by type Commented Mar 6, 2018 at 9:56
  • 1
    What are the values in your array exactly? Please provide more details. Commented Mar 6, 2018 at 17:24

1 Answer 1

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.