如何在EXC_BAD_INSTRUCTION上添加例外? [英] How can i put an exception on EXC_BAD_INSTRUCTION?

查看:96
本文介绍了如何在EXC_BAD_INSTRUCTION上添加例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在以下行中添加例外:

I'm trying to put an exception for the following line:

let someData Int = Int(anArray[0])!

我想要异常,以便它是字符串而不是整数时忽略该异常。

I want the exception so that it ignores it if its a string instead of an integer.

我是新手,但是在python中,我可以执行以下操作:

Im new to swift, but in python i could just do the following:

try:
    let someData Int = Int(anArray[0])!
except:
    pass

我尝试了以下操作:

guard let someData Int = Int(anArray[0])! else {
    print("error")
}

let someData Int = try! Int(anArray[0])!

我正在使用swift 3

I'm using swift 3

推荐答案

您错过了正确的解决方案:

You missed the proper solution:

if let someData = Int(anArray[0]) {
    // someData is a valid Int
}

或者您可以使用 guard

guard let someData = Int(anArray[0]) else {
    return // not valid
}

// Use someData here

请注意,完全没有使用。除非您知道它不会失败,否则不要强行打开它们。

Note the complete lack of the use of !. Don't force-unwrap optionals unless you know it can't fail.

这篇关于如何在EXC_BAD_INSTRUCTION上添加例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆