¿Cómo filtrar la matriz usando el elemento en otra matriz en Swift?

Tengo dos arreglos

let toBeFiltenetworking = ["star0", "star2", "star1", "star0", "star3", "star4"] let theFilter = ["star1", "star3"] 

¿Cómo filtrar la primera matriz usando la segunda matriz? En realidad, theFilter se puede cambiar dinámicamente, por ejemplo,

 let theFilter = ["star2"] or maybe let theFilter = ["star0", "star4", "star2"] 

Gracias por tu ayuda 🙂

Usar operaciones de set

 Set(toBeFiltenetworking).intersection(Set(theFilter)) 

Lea más: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

este parece ser un tema hoy 🙂 aprovechando otra gran respuesta, sugeriría usar el método intersect(_:) en un Set :

 let toBeFiltenetworking = ["star0", "star2", "star1", "star0", "star3", "star4"] let theFilter = ["star1", "star3"] let filtenetworking = Set(toBeFiltenetworking).intersect(theFilter) // => ["star1", "star3"] of type Set<String> // ...if you actually need an array, you can get one using Array(filtenetworking) 

También puede filtrar Struct array también

 struct myStruct { var userid:String; var details:String; init() { userid = "default value"; details = "default"; } }; var f1 = myStruct(); f1.userid = "1"; f1.details = "Good boy"; var f2 = myStruct(); f2.userid = "2"; f2.details = "Bad boy"; var f3 = myStruct(); f3.userid = "3"; f3.details = "Gentleman"; var arrNames1:Array = [f1,f3]; var arrNames2:Array = [f3,f1,f2]; let filtenetworkingArrayStruct = arrNames1.filter( { (user: myStruct) -> Bool in return arrNames2.contains({ (user1: myStruct) -> Bool in return user.userid == user1.userid; }) }) print(filtenetworkingArrayStruct) 

Para Set debes conformar el protocolo Hashable

 class mytestclass: Hashable { var userid:Int ; var details:String; var hashValue: Int { return self.userid } init(userid: Int, details:String) { self.userid = userid; self.details = details; } } func ==(lhs: mytestclass, rhs: mytestclass) -> Bool { return lhs.userid == rhs.userid } var t1 = mytestclass(userid: 1,details: "Good boy"); var t2 = mytestclass(userid: 2,details: "bad boy"); var t3 = mytestclass(userid: 3,details: "gentle man"); var classArrayNames:Set<mytestclass> = [t1,t2]; var classArrayNames2:Set<mytestclass> = [t3,t1,t2]; let result = Set(classArrayNames).intersect(classArrayNames2)