2

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...

Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72
Trung Trịnh
  • 49
  • 1
  • 3
  • 11
  • recorder.url.lastPathComponent probably returns a String?, which is an optional String. Your constructor takes a String (not optional). Therefore, you need to unwrap your optional String in order to use it to create the RecordedAudio – Will M. Aug 18 '15 at 15:01
  • You right @WillM. Thanks a lot – Trung Trịnh Aug 19 '15 at 13:43

1 Answers1

2

lastPathComponent returns an optional String:

enter image description here

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)
Avt
  • 16,927
  • 4
  • 52
  • 72