0

I have an array that I want sorted alphabetically (for the most part). For example I want an array of string to be sorted A-Z with the exception of elements starting with "g", I want elements starting with "g" to be last (or first if that's easier) in the array.

Example:

let list = ["apple", "car", "boat", "zebra", "ghost", "far"]

sorted should be:

["apple", "boat", "car", "far", "zebra", "ghost"]

How would one accomplish this?

2 Answers 2

1

You could use sorted(by:) and compare cases that start with "g" and then fallback to normal String comparison if that doesn't happen:

let sorted = list.sorted { a, b in
    if a.first == "g" && b.first != "g" { return false }
    if b.first == "g" && a.first != "g" { return true }
    return a < b
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think a single expression such as (!$0.hasPrefix("g") && $1.hasPrefix("g")) || (!$0.hasPrefix("g") && $0 < $1) works too, right?
0

I would split it into 2 arrays, sort each of them, then combine them again.

let list = ["apple", "car", "boat", "zebra", "ghost", "far"]
let listWithoutG = list.filter { !$0.hasPrefix("g") }
let listOnlyG = list.filter { $0.hasPrefix("g") }

let sorted = listWithoutG.sorted() + listOnlyG.sorted()
print("Sorted: \(sorted)")

Result:

Sorted: ["apple", "boat", "car", "far", "zebra", "ghost"]

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.