Value of optional type 'String?' not unwra

2020-04-14 04:11发布

问题:

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)