[英]swift convert string to float
I have a table: 我有一张桌子:
let CTCSStable:[String] = [ "67.0 ", "69.3 ", "71.9 "]
I need to convert a selected entry to be a string equal to ten times the numeric value of the entry. 我需要将选定的条目转换为等于该条目的数值十倍的字符串。
var tempCTCSS:String = self.CTCSStable[ctcssIndex]
let tempCTCSSF:Float = Float(tempCTCSS)!
This throws an exception: 这将引发异常:
fatal error: unexpectedly found nil while unwrapping an Optional value
致命错误:解开Optional值时意外发现nil
The reason you are getting the crash is because Float(tempCTCSS)!
您崩溃的原因是因为
Float(tempCTCSS)!
is trying to convert tempCTCSS
into a Float, but it fails, and then you force unwrap that value and it is nil, so it crashes. 正在尝试将
tempCTCSS
转换为Float,但失败,然后您强制拆开该值,并且它为nil,因此崩溃。
The reason why it fails to convert that string to a Float is because there is white space. 它无法将字符串转换为Float的原因是因为存在空格。 Try removing the spaces.
尝试删除空格。
I would never force unwrap (ie !
) unless you know that that value is there. 除非您知道该值存在,否则我绝不会强行打开包装(即
!
)。 The best practice would be to wrap that value in an if let
statement. 最佳做法是将该值包装在
if let
语句中。 That conditionally unwraps the value and prevents the crash 有条件地解开值并防止崩溃
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.