简体   繁体   English

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

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

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()
                }

When you write let lvt=self?.lastVibrationTime when using self? 当你使用self?时写let lvt=self?.lastVibrationTime self? your lvt variable is optional, you have to unwrap it before using it, you have many solutions to fix this error: 你的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...
}

All your optionals need to be unwrapped. 您需要打开所有选项。 So lvt should become lvt! 所以lvt应该成为lvt!

Word of Caution Unwrapping 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)

With this line: 有了这条线:

let lvt = self?.lastVibrationTime

You're acknowledging self is optional. 你承认self是可选的。 So if it's nil then lvt would be nil; 所以,如果它是nillvt将为零; if self is not nil , then you'll get the last vibration time. 如果self不是nil ,那么你将获得最后的振动时间。 Because of this ambiguity, lvt is not of type Double but an optional, Double? 由于这种歧义, lvt不是Double类型,而是可选的Double? .

If you're certain self will not be nil, you can force unwrap it: 如果你确定self不会是零,你可以强制打开它:

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

If self is nil though, the app will crash here. 如果self为nil,应用程序将在这里崩溃。

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 else case here if you have some code to perform in the case of nil. 这意味着如果你有一些代码要在nil的情况下执行,你可能需要一个else案例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM