Crashalot Crashalot - 1 year ago 224
Swift Question

Swift 3: sorting arrays with sort function: seeing error of Ambiguous use of 'sort(comparator:)'

This code generates this error:

Ambiguous use of 'sort(comparator:)'

chars.sort {
let s0 = $0 as? String
let s1 = $1 as? String
if array.index(of: s0) == array.index(of: s1) {
} else if array.index(of: s0) < array.index(of: s1) {
} else {

Other SO posts suggested casting the arguments of the
function to Strings, but the error persists. Can anyone explain why?

Answer Source

If you have an array like this

let chars: [Any] = ["g", "c", "a"]

and you want to sort it using the orders the elements into another array

let orders = ["a", "b", "c", "e", "f"]

you can simply write

let sorted = chars
    .flatMap { $0 as? String }
    .sorted { orders.index(of:$0) ?? Int.max < orders.index(of: $1) ?? Int.max }

// print(sorted) 
// ["a", "c", "g"]