简体   繁体   English

如何在 IOS swift 中将 Double 转换为 Int

[英]how to convert Double to Int in IOS swift

在此处输入图片说明

tmp turned out to be nil in runtime. tmp 在运行时结果为零。 magneticField.x is a Double and when I printed it directly out it has a value. magneticField.x 是一个 Double,当我直接打印出来时,它有一个值。

The casting of the Double to an Int will work as written.将 Double 转换为 Int 将按书面方式工作。 The problem is that for some reason at runtime self.motion.magnetometerData is nil, so tmp becomes nil.问题是由于某种原因在运行时 self.motion.magnetometerData 为零,因此 tmp 变为零。

It's usually better to safely unwrap optionals, such as:通常最好安全地解开可选项,例如:

let tmp = self.motion.magnetometerData?.magneticField.x
if let tmpValue = tmp {
    let tmpInt = Int(tmpValue)
    print(tmpInt) //And whatever else
}

Or, if you intend not to continue if it ends up being nil, use a guard:或者,如果您打算在结果为零时不继续,请使用守卫:

guard let tmp = self.motion.magnetometerData?.magneticField.x else {
    return //Or whatever is appropriate when the value is nil
}

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

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