简体   繁体   中英

How can I safely unwrap an optional?

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!)





}

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")

}

你可以这样

print("Artist: " + (artist ?? "no artist"))

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:

  1. Force unwrap: !

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!)
}
  1. Optional binding: 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!")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM