0

I have this struct of locations:

struct Location: Identifiable, Codable {
    var id: String
    var name: String
    var country: String
}

I can easily sort this by name:

self.userData = self.userData.sorted(by: {$0.name < $1.name })

But I also want the ability to put locations with a particular country first in the list.

I tried this:

self.userData.sorted(by: { ($0.country == "United States"), ($0.name < $1.name) })

but I get an error "Consecutive statements on a line must be separated by ;".

How can I sort alphabetically by a particular country first? Then sort the remaining locations alphabetically by the name property.

3 Answers 3

2

You probably still want to sort by name if both locations have a country of "United States".

let topCountries: Set<String> = ["United States"]

userData.sorted { a, b in
    switch (topCountries.contains(a.country), topCountries.contains(b.country)) {
    case (true, false): return true
    case (false, true): return false
    default: return a.name < b.name
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Look at the full syntax of passing a closure. You are using a shortcut for the special case that the closure consists of one return statement only. Expand it to the full closure syntax where you can use arbitrary code, then write the code you need.

Comments

0

The solution @rob mayoff gave worked. Here is my final piece of code:

let topCountries: Set<String> = ["United States"] // or the user's country
        
    filteredLocations = allLocations.filter { $0.name.contains(searchText) }.sorted { a, b in
                switch (topCountries.contains(a.country), topCountries.contains(b.country)) {
                    case (true, false): return true
                    case (false, true): return false
                    default: return a.name < b.name
                }
            }

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.