Swift错误:可选types'Double?'的值? 不解开

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

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

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

你所有的可选项都需要打开。 所以lvt应该变成lvt!

注意事项解开一个没有值的可选项将会抛出一个exception。 所以确保你的lvt不是零是个好主意。

 if (lvt != nil) 

用这一行:

 let lvt = self?.lastVibrationTime 

你承认self是可选的。 所以如果是nil那么lvt将是零; 如果self不是nil ,那么你会得到最后的振动时间。 由于这种模糊性, lvt不是Doubletypes的,而是可选的Double?

如果你确定self不会是零,你可以强行解开它:

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

如果self是零,但应用程序将崩溃在这里。

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

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

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