You have not defined how you want the elements in array1
but not in array2
to be sorted. This solution assumes you want to sort those not-found elements by their numeric value:
var array1 = [100, 40, 10, 50, 30, 20, 90, 70]
var array2 = [50, 20, 100, 10, 30]
array1.sort {
let index0 = array2.index(of: $0)
let index1 = array2.index(of: $1)
switch (index0, index1) {
case (nil, nil):
return $0 < $1
case (nil, _):
return false
case (_, nil):
return true
default:
return index0! < index1!
}
}
print(array1) // [50, 20, 100, 10, 30, 40, 70, 90]
// ^ order not defined in array2