Gustavo Payano
Gustavo Payano

Reputation: 45

Trying to pass nil but compiler keeps making me force unwrap an optional value Swift

I am working on an app, and I created the following function:

func initMPVideoPlayer(videoUrl: NSString?) {
    var fileURL: NSURL = NSURL(string: videoUrl)
    self.videoController = MPMoviePlayerController()
    self.videoController?.contentURL = fileURL

    self.videoController?.controlStyle = MPMovieControlStyle.None
    self.videoController?.scalingMode = MPMovieScalingMode.AspectFill
    self.videoController?.setFullscreen(true, animated: true)
    self.videoController?.movieSourceType = MPMovieSourceType.Streaming
    self.videoController?.view.frame = self.view.bounds
    MBProgressHUD.showHUDAddedTo(self.videoController?.backgroundView, animated: true)

    self.view.insertSubview(self.videoController!.view, atIndex: 2)

    let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:("showView"))
    tapGesture.delegate = self
    tapGesture.numberOfTapsRequired = 1
    self.videoController?.view.addGestureRecognizer(tapGesture)

    self.videoController?.prepareToPlay()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "videoPlayBackDidFinish", name: MPMoviePlayerPlaybackDidFinishNotification, object: self.videoController)


}

I call the function in the view controllers viewdidload method, and I pass it nil, like so: self.initMPVideoPlayer(nil) but for some reason the compiler gives me an error, and tells me that i should force unwrap this line within the function like so: var fileURL: NSURL = NSURL(string: videoUrl!)! However that can't be correct because I am deliberately passing in nil so why is it telling me to do something that clearly will not work. I've been trying to figure out a solution but have yet to find one....

Upvotes: 0

Views: 81

Answers (1)

Matthias Bauch
Matthias Bauch

Reputation: 90117

The compiler is complaining because NSURL(string:) does not allow an optional. At this point the compiler doesn't care what you pass in deliberately. If a method only accepts non-optionals you can't pass in an optional.

The solution might be to not allow optionals in initMPVideoPlayer(videoUrl:).

func initMPVideoPlayer(videoUrl: NSString) {
    var fileURL: NSURL = NSURL(string: videoUrl)
    ...
}

If there is really a reason to create a MPMoviePlayerController without an URL you can use conditional unwrapping instead of force unwrapping. Force unwrapping is only useful if a variable can't contain nil.

Something like this:

func initMPVideoPlayer(videoUrl: NSString?) {
    self.videoController = MPMoviePlayerController()
    if let videoUrl = videoUrl {
        var fileURL: NSURL = NSURL(string: videoUrl)
        self.videoController?.contentURL = fileURL
    }
    ...
}

Upvotes: 1

Related Questions