Swift:确定从字符串转换为整数是否成功

时间:2016-07-30 15:42:43

标签: swift casting

以下是我的代码

func contactForUpdates() -> Int {
    //contact server for most recent version
    let versionURL = settings.versionURL

    if let url = URL(string: versionURL) {
        do {
            let contents = try NSString(contentsOf: url, usedEncoding: nil)
//NEXT LINE IS WHERE THE QUESTIONS LIES
            return Int(contents as String)!
        } catch {
            // contents could not be loaded
            processError("Current version could not be loaded.")
            return Int(0)
        }
    } else {
        // the URL was bad!
        processError("Current version could not be loaded--URL was bad.")
        return Int(0)
    }
}

如果加载了URL,它将返回一个整数。糟糕的互联网连接,例如需要在互联网访问之前登录的机场,不会返回整数,而是返回请求登录的完整HTML页面。使用return Int(contents as String)!强制转发,会产生错误fatal error: unexpectedly found nil while unwrapping an Optional value

我认为这会在我写这个时运行catch语句,但它会返回致命错误。我怎么能抓到这个?

3 个答案:

答案 0 :(得分:2)

如果0代表您的错误,您可以执行以下操作:

return Int(contents as String) ?? 0

??被称为" nil合并运算符"。如果它不是nil,则返回第一个值,否则返回第二个值。

如果您想要更强大的处理,可以使用guard ...

guard let value = Int(contents as String) else {
    processError("Something went horribly wrong")
    return 0
}

return value

答案 1 :(得分:0)

那是因为您强制将可选值强制为非可选值。

您必须检查转换是否可行:

if let number = Int(contents as String) {
    return number
}
return -1 // Or something you will recognise as error

答案 2 :(得分:0)

func contactForUpdates() -> Int {
    //contact server for most recent version
    let versionURL = settings.versionURL

    if let url = URL(string: versionURL) {
        do {
            let contents = try NSString(contentsOf: url, usedEncoding: nil)
            if let vers = Int(contents as String) {
                return vers
            }
            else {
                processError("Current version could not be loaded--Possibly proxy interception")
                return Int(0)
            }
            //return Int(contents as String)!
        } catch {
            // contents could not be loaded
            processError("Current version could not be loaded.")
            return Int(0)
        }
    } else {
        // the URL was bad!
        processError("Current version could not be loaded--URL was bad.")
        return Int(0)
    }
}

修复了错误,尽管do / catch运行了catch语句。我不知道为什么?我希望有人可以回答这个问题,但除此之外,这句话也解决了这个问题。