Reputation: 193
I have created a model to store data about a song. On a view controller I want to only show songs by a particular artist instead of showing all the songs stored in the database.
I have tried using map and filter but didn't understand it fully, is there another method I could try?
let selectedArtist = artists[indexPath.row]
The code above is the selected the artist which is taken from the didSelect method when choosing which artist they want to display songs by. It has the type of the model - Song which holds song, artist, album.
When clicking on the selected artist, I expect the model to be filtered to only show songs by the chosen artist. This will be stored in an array matching the model or stored in an array called selectedSongs which are added to the array when being filtered matching the artist name.
Upvotes: 0
Views: 701
Reputation: 51993
Assuming two types, Song and Artist
struct Song {
var title: String
var artist: Artist
var album: String
}
struct Artist {
var name: String
}
Then in the view controller you can have an array filteredSongs and a function that performs the filtering
class ExampleViewController {
var songs = [Song]()
var filteredSongs: [Song]?
func filterSongs(byArtist artist: Artist) {
filteredSongs = songs.filter { song in
song.artist.name == artist.name
}
}
//...
}
so you can then use it by doing
let selectedArtist = artists[indexPath.row]
filterSongs(byArtist: selectedArtist)
Upvotes: 0