我的实时应用程序在 Float 到 Int 转换线上随机崩溃。
我无法弄清楚为什么它会崩溃并且无法重现它,因为它是实时应用程序上的随机崩溃。关于如何修复崩溃有什么建议吗?
崩溃日志
Crashed: com.apple.main-thread
0 MyApp 0x100703778 closure #1 in MyViewController.getBalance(isRefreshed:) + 797 (MyViewController.swift:797)
1 MyApp 0x1005c7670 closure #1 in closure #1 in fetchtBalance(completed:) + 185 (Utils.swift:185)
2 MyApp 0x10051ab10 thunk for @escaping @callee_guaranteed () -> () + 4335790864 (<compiler-generated>:4335790864)
3 libdispatch.dylib 0x1ae908b7c _dispatch_call_block_and_release + 32
4 libdispatch.dylib 0x1ae909fd8 _dispatch_client_callout + 20
5 libdispatch.dylib 0x1ae915cc8 _dispatch_main_queue_callback_4CF + 968
6 CoreFoundation 0x1aebdee0c __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
7 CoreFoundation 0x1aebd9b68 __CFRunLoopRun + 1980
8 CoreFoundation 0x1aebd9084 CFRunLoopRunSpecific + 480
9 GraphicsServices 0x1b8e27534 GSEventRunModal + 108
10 UIKitCore 0x1b2d49670 UIApplicationMain + 1940
11 MyApp 0x1004ec6b8 main + 20 (ClientMyProfileViewController.swift:20)
12 libdyld.dylib 0x1aea58e18 start + 4
代码
import UIKit
var balance: String!
var cost: String?
func getBalance () {
fetchBalance() { (result, error) in
guard let balanceFloatValue = Float(balance!) else {
print("Error")
return
}
guard let costFloat = Float(cost!) else {
print("Error")
return
}
let costPerSec = costFloat / 60
let talkTime = balanceFloatValue / costPerSec
let talkTimeInt = Int(talkTime) // Line No. 797 Crash here
// ....
}
}
最佳答案
导致此错误的最可能原因是值本身
let a:Float = 9999999999999999999999.9
let b = "0.000000000000000000001"
let c:Float = a/Float(b)!
let x = Int(c) // <- Crash here
0/0 会让你崩溃:让 c:Float = a/Float(b)!所以不是这样,但是任何其他可以使 talkTime 在 Int 之外的东西都会让你崩溃 这也可以解释为什么您只会随机遇到错误,因为它仅适用于使该除法为 NaN 或 inf 或 int 之外的值,如 bg2b 所说
关于ios - Float 到 Int 转换时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59430096/