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

妖精的绣舞 提交于 2019-12-02 04:49:17

问题


I define a class in Swift like that:

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

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

After that, I declare the global var of this one in controller

var recordedAudio: RecordedAudio!

And then, create the instance in this function:

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

But I got the error message in line I create the instance of RecordedAudio:

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

Could you help me this case? I am a beginner of Swift...


回答1:


lastPathComponent returns an optional String:

but your RecordedAudio seems to require String not String?. There are two easy ways to fix it:

Add ! in case you are sure lastPathComponent will never return nil

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

or

Use a default title in case lastPathComponent is nil

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


来源:https://stackoverflow.com/questions/32075950/value-of-optional-type-string-not-unwrapped-did-you-mean-to-use-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!