简体   繁体   中英

Swift how to filter 2 array

I'm new in Swift, and I can't figure out how to filter these 2 arrays

var arrayOfFavoriteRoomsId = ["1", "2"]
var arrayOfRooms = [
    VoiceRoom(id: "1", title: "Room1", description:"Test room1"), 
    VoiceRoom(id: "2", title: "Room2", description:"Test room2"), 
    VoiceRoom(id: "3", title: "Room3", description:"Test room3")
]

The final array should look like this

var filteredArray = [
        VoiceRoom(id: "1", title: "Room1", description:"Test room1"), 
        VoiceRoom(id: "2", title: "Room2", description:"Test room2")
    ]

This is what my model looks like

struct VoiceRoom: Identifiable, Decodable {
  var id: String
  var title: String
  var description: String
}
arrayOfRooms.filter { room in
    arrayOfFavoriteRoomsId.contains(room.id)
}

If you want to sort them as well:

arrayOfRooms.filter { room in
    arrayOfFavoriteRoomsId.contains(room.id)
}.sorted(by: { $0.id < $1.id })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM