可选类型 'String?' 的值未展开;你是不是想用'!'要么 '?'?

Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

我在 Swift 中定义一个 class 是这样的:

class RecordedAudio: NSObject {
    var title: String!
    var filePathUrl: NSURL!

    init(title: String, filePathUrl: NSURL) {
        self.title = title
        self.filePathUrl = filePathUrl
    }
}

之后,我在controller中声明这个的全局变量

var recordedAudio: RecordedAudio!

然后,在此函数中创建实例:

func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
        if(flag){
            // save recorded audio
           recordedAudio = RecordedAudio(title: recorder.url.lastPathComponent, filePathUrl: recorder.url)
...

但是我在创建 RecordedAudio 实例时收到错误消息:

Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

你能帮我这个案子吗?我是 Swift...

的初学者

lastPathComponent returns 一个可选字符串:

但是您的 RecordedAudio 似乎需要 String 而不是 String?。 有两种简单的方法可以修复它:

如果您确定 lastPathComponent 永远不会 return nil

,请添加 !
recordedAudio = RecordedAudio(title: recorder.url.lastPathComponent!, filePathUrl: recorder.url)

在 lastPathComponent 为 nil 的情况下使用默认标题

recordedAudio = RecordedAudio(title: recorder.url.lastPathComponent ?? "Default title", filePathUrl: recorder.url)