Edu
Edu

Reputation: 470

Getting fatal error due to a nil in swift

Using Xcode, Im getting a fatal error due to a nil received in swift 2.0. The constant declared below is the point where the app crashes because the mediaItem response is nil:

let url: NSURL? = NSURL(string: (self.mediaItem?[0].url)!)

how can I avoid this issue?

Upvotes: 0

Views: 285

Answers (1)

Midhun MP
Midhun MP

Reputation: 107231

The crash is happening due to (self.mediaItem?[0].url)!. If the self.mediaItem?[0].url returns a nil value then the statement changes like: (nil)! and crashes the application. Also you need to handle the array out of bounds exception, that can occur if your mediaItems array is empty.

You can fix it like:

if let mediaArray = self.mediaItem where mediaArray.count > 0
{
   if let urlString = mediaArray[0].url
   {
     let url: NSURL? = NSURL(string: urlString)
   }
}

Upvotes: 1

Related Questions