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

后端 未结 1 723
旧巷少年郎
旧巷少年郎 2021-01-22 08:20

I define a class in Swift like that:

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

    init(title: String, filePathUrl: NSU         


        
1条回答
  •  醉梦人生
    2021-01-22 08:57

    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)
    

    0 讨论(0)
提交回复
热议问题