【问题标题】:Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?可选类型“字符串?”的值未拆封;你的意思是用'!'要么 '?'?
【发布时间】:2015-11-11 14:22:33
【问题描述】:

我在 Swift 中这样定义一个类:

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

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

之后,我在控制器中声明了这个的全局变量

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 实例的行中收到错误消息:

可选类型“字符串?”的值未拆封;你的意思是用'!'还是“?”?

你能帮我这个案子吗?我是 Swift 的初学者...

【问题讨论】:

  • recorder.url.lastPathComponent 可能返回一个字符串?,这是一个可选的字符串。您的构造函数接受一个字符串(不是可选的)。因此,您需要解开可选的 String 以便使用它来创建 RecordedAudio
  • 你说得对@WillM。非常感谢

标签: swift constructor unwrap


【解决方案1】:

lastPathComponent 返回一个可选字符串:

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

添加 ! 以防你确定 lastPathComponent 永远不会返回 nil

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

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

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

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多