我使用一种服务,该服务发送回类型为String
的值,其中包含像Double
这样的浮点数,例如"1240.86"。 我想将其转换为Int
,当我尝试像这样转换时Int(stringObject)
当值具有浮点数时,转换失败。 如何投射? 谢谢!
分两步尝试:
if let aDouble = Double(someString) {
let someInt = Int(aDouble)
}
或者可能:
let someInt = Int(Double(someString) ?? 0)
尽管后者有点笨拙,因为如果字符串不是有效数字,您可能不想强制使用0
的值。
您可以使用map(_:)
的Optional
方法选择性地将转换(特别是初始化方式(从String
链接到Double
,然后从Double
链接到Int
的转换,并在未nil
的情况下有条件地绑定生成的整数(即成功转换(:
let str = "1240.86"
if let number = Double(str).map(Int.init) {
// number is of type Int and, in this example, of value 1240
}
你可以用点分隔字符串.
:
func printInt(from str: String) {
let intValue = Int(str.components(separatedBy: ".")[0]) ?? 0
print(intValue)
}
printInt(from: "1234.56") // 1234
printInt(from: "1234") // 1234
printInt(from: "0.54") // 0
printInt(from: ".54") // 0
printInt(from: "abc") // 0