Hi,
So thanks to Eskimo and his group by trick (very useful), I just finished a pretty good version of my artists - albums - tracks tree.
Here is my playground :
import Cocoa
import iTunesLibrary
do {
let lib = try ITLibrary(apiVersion: "1.1")
let theITTracks = lib.allMediaItems.filter({$0.mediaKind == .kindSong})
let theTracksByArtist = Dictionary(grouping: theITTracks, by: { $0.artist?.name } )
var theArtistsTree = [Artist]()
for(artistKey, tracksByArtist) in theTracksByArtist {
print("artistKey >>>", artistKey)
print("/////////")
let theAlbumsTracks = tracksByArtist.map{ $0 }
let theITArtist = theAlbumsTracks.first?.artist
let theArtist = Artist(theITArtist: theITArtist!)
let theArtistAlbums = Dictionary(grouping: theAlbumsTracks, by: { $0.album.persistentID } )
for (albumID, tracksAlbum) in theArtistAlbums {
let theTracksAlbum = tracksAlbum.map { $0 }
let theITAlbum = theTracksAlbum.first?.album
let theAlbum = Album(theITAlbum: theITAlbum!)
print(theTracksAlbum.first?.album.title)
print("++++")
for track in theTracksAlbum {
print(track.title)
let theTrack = Track(theITTrack: track)
theAlbum.tracks.append(theTrack)
}
print("***************")
theArtist.albums.append(theAlbum)
}
theArtistsTree.append(theArtist)
print("---------------------------------------------------------------------------------------------------")
}
} catch let error {
print(error)
}
But I have a bunch of problems to solve like the sort of the dictionary grouped by artist.
I tried :
let theTracksByArtist = Dictionary(grouping: theITTracks, by: { ($0.artist?.name)! } ).sorted(by: { $0.key.localizedStandardCompare($1.key) == .orderedAscending })
It is working until the moment an artist nil is parsed :
Multiline
error: Execution was interrupted, reason: EXC_BREAKPOINT (code=1, subcode=0x1006c2ad8).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
So how to avoid this error ? Do I need to test the artist?.name before to compare it ? How to ?
Thx.