xcode Swift 错误:可选类型“Double?”的值 没有打开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29373958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:54:06  来源:igfitidea点击:

Swift error : value of optional type 'Double?' not unwrapped

iosiphonexcodeswift

提问by AVEbrahimi

I am newbie in Swift, what is this error :

我是 Swift 新手,这是什么错误:

let lvt=self?.lastVibrationTime
let delta=self!.deltaTime
let sens=self!.shakeSensitivity
let time:Double = CACurrentMediaTime()

//error is on `lvt` and says : Error:(37, 27) value of optional type 'Double?' not unwrapped; did you mean to use '!' or '?'?
if time - lvt > delta && data.userAcceleration.x < sens {
                    println("firmly shaken!")
                    self?.vibrateMe()
                }

回答by bsarr007

When you write let lvt=self?.lastVibrationTimewhen using self?your lvt variable is optional, you have to unwrap it before using it, you have many solutions to fix this error:

当你写的let lvt=self?.lastVibrationTime时候使用self?你的 lvt 变量是可选的,你必须在使用它之前解开它,你有很多解决这个错误的解决方案:

1. let lvt = self?.lastVibrationTime ?? 5 // 5 is the default value, you can use the value you want

2. let lvt = self!.lastVibrationTime

3. You can unwrap the value before use it:
if let lvt = self?.lastVibrationTime {
    // your code here...
}

回答by Shamas S - Reinstate Monica

All your optionals need to be unwrapped. So lvtshould become lvt!

您的所有选项都需要展开。所以lvt应该变成lvt!

Word of CautionUnwrapping an optional which doesn't have a value will thrown an exception. So it might be a good idea to make sure your lvt isn't nil.

注意事项展开没有值的可选项将引发异常。因此,确保您的 lvt 不为零可能是个好主意。

if (lvt != nil)

回答by gregheo

With this line:

有了这条线:

let lvt = self?.lastVibrationTime

You're acknowledging selfis optional. So if it's nilthen lvtwould be nil; if selfis not nil, then you'll get the last vibration time. Because of this ambiguity, lvtis not of type Doublebut an optional, Double?.

你承认self是可选的。因此,如果是,nillvt为零;如果self不是nil,那么您将获得最后一次振动时间。由于这种歧义,,lvt不是类型Double而是可选的,Double?

If you're certain selfwill not be nil, you can force unwrap it:

如果您确定self不会为零,则可以强制打开它:

let lvt = self!.lastVibrationTime // lvt is a Double

If selfis nil though, the app will crash here.

如果self为零,应用程序将在此处崩溃。

To be safe, you can use optional binding to check for the value:

为了安全起见,您可以使用可选绑定来检查值:

if let lvt = self?.lastVibrationTime {
  // do the comparison here
}

That means you might need an elsecase here if you have some code to perform in the case of nil.

这意味着else如果您有一些代码要在 nil 的情况下执行,那么您可能需要一个案例。