cannot subscript a value of type [MPMediaItem]

2019-08-06 13:46发布

问题:

I am trying to execute this code in order to get all the music playlists that the users can have on their phones.

    var queryPlaylists = MPMediaQuery.playlistsQuery()
    print(queryPlaylists.collections[0])

However, when I try to access any of the elements of queryPlaylists.collections I get a compilation error:

Cannot subscript a value of type [MPMediaItem].

This does not make any sense to me since the above in an array. In addition this used to work before xcode 7.0.

回答1:

I figured out in order to access the elements in the queryPlaylists you need to create a new variable and cast it to [MPMediaPlaylist] as

var playlists = queryPlaylists.collections as! [MPMediaPlaylist]

now you can access the elements of playlists