可选类型“String?”的值不解包;你的意思是使用'!要么 '?'? [英] Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

查看:225
本文介绍了可选类型“String?”的值不解包;你的意思是使用'!要么 '?'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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(record:AVAudioRecorder !, successfully flag:Bool){
if(flag){
//保存录制的音频
recordedAudio = RecordedAudio(title:recorder.url.lastPathComponent,filePathUrl:recorder.url)
...

但我在行中创建了RecordedAudio的实例的错误消息:


可选类型String? ;你是说使用'!'还是'?'?


你能帮我一下吗?我是Swift的初学者...

解决方案

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)


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

解决方案

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)

这篇关于可选类型“String?”的值不解包;你的意思是使用'!要么 '?'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆