2017-08-02 3 views
0

Ich frage mich, wie von einem anderen Array in Swift 3Array nach anderem Array sortieren?

sie ein Array sortieren sagen, ich habe:

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] 

und ich möchte das ursprüngliche Array sortieren, sein:

[channel3, channel2, channel1, channel4, channel5] 

Gibt es eine schnelle und wenig aufwendige Möglichkeit, dies zu tun?

Antwort

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

Nun, das war einfach genug! Vielen Dank. –

0

Zip ist viel einfache Methode, dies zu erreichen

// 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} 

Hoffe, es hilft