2017-11-10 7 views
0

私は次の行のために例外を置くしようとしている:EXC_BAD_INSTRUCTIONに例外を設定するにはどうすればよいですか?

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

その文字列の代わりに、整数の場合、それはそれを無視するように、私は例外をしたいです。

迅速に新しいイムが、Pythonで私はちょうど行うことができ、次の

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

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

私は」:

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

私は、次の試してみましたスウィフトを使用して3

+0

* * 'STRING'はオプションがに記載の結合と呼ばれているから' Int'を作成するための例外を入れて[ Swift Language Guide:The Basics](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html);-) – vadian

答えて

1

あなたマイル

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

それともguardを使用することができます:適切な解決策をssed

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

// Use someData here 

!の使用の完全な欠如を注意してください。オプションを強制的にアンラップしないでください。スウィフトは

1

は、のtry-catchブロックは次のようになります。

do { 
    //call a throwable function, such as 
    try JSONSerialization.data(withJSONObject: data) 
} catch { 
    //handle error 
} 

しかし、あなただけ常にドキュメントのキーワードをスローでマークされていスロー可能機能からエラーをキャッチすることができます。 tryキーワードはthrowable関数でのみ使用でき、do-catchブロックはdoブロック内でtryキーワードを使用すると効果があります。

キャッチしようとしている強制的なキャスト/アンラッピングの例外など、他の種類の例外をキャッチすることはできません。

適切な処理方法オプションのバインディングを使用する場合は、オプションの値。

guard let someData = Int(anArray[0]) else { 
    print("error") 
    return //bear in mind that the else of a guard statement has to exit the scope 
} 

スコープを終了したくない場合:スウィフトで

if let someData = Int(anArray[0]) { 
    //use the integer 
} else { 
    //not an integer, handle the issue gracefully 
} 
関連する問題