I'm working on a music application that is able to play a playlist of songs, I have two data types representing a song in my project; "Track" which is of NSManagedObject for songs saved on the device by the user, and "JSONTrack" which represents songs decodable from a json web service. Users should be able to add both types to a an array of playlist. How do I achieve this with Swift, making an array for the different data types and work on that array: My current code handling one of the data types looks like this:
var playlistTracks = [Track]()
@objc fileprivate func handlePrevTrack() {
if playlistTracks.isEmpty {
return
}
let currentTrackIndex = playlistTracks.index { (tr) -> Bool in
return self.track?.trackTitle == tr.trackTitle && self.track?.albumTitle == tr.albumTitle
}
guard let index = currentTrackIndex else { return }
let prevTrack: Track
if index == 0 {
let count = playlistTracks.count
prevTrack = playlistTracks[count - 1]
} else {
prevTrack = playlistTracks[index - 1]
}
self.track = prevTrack
}
@objc func handleNextTrack() {
if playlistTracks.count == 0 {
return
}
let currentTrackIndex = playlistTracks.index { (tr) -> Bool in
return self.track?.trackTitle == tr.trackTitle && self.track?.albumTitle == tr.albumTitle
}
guard let index = currentTrackIndex else { return }
let nextTrack: Track
if index == playlistTracks.count - 1 {
nextTrack = playlistTracks[0]
} else {
nextTrack = playlistTracks[index + 1]
}
self.track = nextTrack
}
handling next and previous selection. I would like to do the same for two different types of songs which are represented by two different data types.