Crashalot Crashalot - 2 months ago 76
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) {
ComparisonResult.orderedSame
} else if array.index(of: s0) < array.index(of: s1) {
ComparisonResult.orderedDescending
} else {
ComparisonResult.orderedAscending
}
}


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

Answer

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"]
Comments