2017-08-02 81 views
0

我想知道如何在斯威夫特3按其他数组排序数组?

让我们说我有排序另一个数组的数组:

struct Channel { 
    var id: Int 
} 

let channel1 = Channel(id: 1) 
let channel2 = Channel(id: 2) 
let channel3 = Channel(id: 3) 
let channel4 = Channel(id: 4) 
let channel5 = Channel(id: 5) 

var original = [channel1, channel2, channel3, channel4, channel5] 
var favorites = [channel3, channel2, channel1, channel4] 

,我想原来的数组排序是:

[channel3, channel2, channel1, channel4, channel5] 

有没有快速和低耗费的方式来做到这一点?

回答

1
favorites.append(contentsOf: original.filter { chanel in 
    !favorites.contains(where: { $0.id == chanel.id }) 
}) 
+0

嗯,这是很简单的!谢谢。 –

0

Zip是多简单的方法来实现这一

// use zip to combine the two arrays and sort that based on the first 
// Your original array 

let combined = zip(array1, array2).sort {$0.0 < $1.0} 
print(combined) // 

// Now use map to extract the individual arrays  
let sorted1 = combined.map {$0.0} 
let sorted2 = combined.map {$0.1} 

希望它可以帮助