Reputation: 99
I am getting the currently playing song from the musicPlayer, and when the artist is nil the app crashes. How do I safely unwrap this, so if there is no artist then the app does not crash rather it just prints no artist in the console?
func getNowPlayingItem() {
if let nowPlaying = musicPlayer.nowPlayingItem {
let title = nowPlaying[MPMediaItemPropertyTitle] as? String
//I want to safely unwrap the artist
let artist = nowPlaying[MPMediaItemPropertyArtist] as? String
print("Song: " + title!)
print("Artist: " + artist!)
print("\n")
arrayOfSongs.append(title!)
}
Upvotes: 0
Views: 408
Reputation: 81
Right now artist
is an optional String (String?
). This means it can either contain a String, or the value nil
. To access the String inside if it exists, you need to unwrap the optional. There are two ways to unwrap an optional:
!
This is what you're doing in your code sample when you do artist!
. The optional is forcibly unwrapped into a String. However, if artist
was actually equal to nil
, the force unwrap will crash your app. So, in order to do this safely, you want to first check if artist == nil
.
if (artist == nil) {
print("it's nil!")
} else {
print("Artist: " + artist!)
}
if let
This is the recommended and less error prone option. This allows us to unwrap optionals without ever using the !
. The !
is a signal to you that this is an unsafe piece of code that can crash if the optional is nil, and you should try to avoid it. This is what optional binding looks like:
if let artist = nowPlaying[MPMediaItemPropertyArtist] as? String {
// This code only runs if the optional was NOT nil
// The artist variable is the unwrapped String
print("Artist: " + artist)
} else {
// This code only runs if the optional nil
print("it's nil!")
}
Upvotes: 1
Reputation: 3155
Think of the exclamation mark as a warning — don't use it unless you're absolutely sure the item can be unwrapped!
So, just change let title
and let artist
into if let
blocks where you can safely use the unwrapped value:
func getNowPlayingItem() {
if let nowPlaying = musicPlayer.nowPlayingItem {
if let title = nowPlaying[MPMediaItemPropertyTitle] as? String {
print("Song: " + title)
arrayOfSongs.append(title)
}
if let artist = nowPlaying[MPMediaItemPropertyArtist] as? String {
print("Artist: " + artist)
}
print("\n")
}
Upvotes: 2