浮点数到整数转换时崩溃

问题描述 投票:1回答:3

我在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

        // ....
    }
}
ios swift floating-point int
3个回答
1
投票

此错误的最可能原因是值本身

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说)的值有效]


0
投票

我认为您正在强行解开余额值。尝试解开转换后的值,例如:“浮点(余额)!”


-1
投票

您可以像这样迅速地将float值转换为Integer值:

© www.soinside.com 2019 - 2024. All rights reserved.