试图传递nil但编译器一直让我强制解包一个可选值Swift

时间:2015-03-03 07:19:46

标签: swift optional

我正在开发一款应用,并创建了以下功能:

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)


}

我在视图控制器viewdidload方法中调用该函数,并将其传递给nil,如下所示:self.initMPVideoPlayer(nil)但由于某种原因,编译器给出了一个错误,并告诉我应该强制打开此行像这样的函数:var fileURL: NSURL = NSURL(string: videoUrl!)!然而,这不是正确的,因为我故意传递nil所以为什么它告诉我做一些显然不起作用的事情。我一直试图找出一个解决方案,但还没找到一个....

1 个答案:

答案 0 :(得分:1)

编译器抱怨,因为NSURL(string:)不允许使用可选项。在这一点上,编译器并不关心你故意传递的内容。如果某个方法只接受非选项,则无法传入可选项。

解决方案可能是不允许initMPVideoPlayer(videoUrl:)中的选项。

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

如果确实有理由创建没有URL的MPMoviePlayerController,您可以使用条件展开而不是强制解包。强制解包仅在变量不能包含nil时才有用。

这样的事情:

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