2017-02-24 5 views
-1

をトロウスロー:機能は実行して機能を終了していないスロー私は、以下の機能を持っている

func doSomething(_ myArray: [Int]) throws -> Int { 

    if myArray.count == 0 { 
     throw arrayErrors.empty 
    } 
    return myArray[0] 
} 

しかし、配列は0に等しい場合には、エラーがスローされますが、それは機能の実行を継続します空の配列を返します。

ifステートメントに行くときに、どのようにして関数を終了できますか?

+3

あなたは、 "空の配列を返す" とはどういう意味ですか?あなたの関数は 'Int'を返します。 – Hamish

+2

あなたがあなたの質問にした陳述は真実ではなく、ほとんどのものはほとんど意味がありません。 * "配列が0のとき*"と言うとき、実際には "配列が空のとき"を意味しますか?また、 "throw"行が実際に呼び出された場合、 'return'行には続かず、何も返されません。 – rmaddy

答えて

1

エラー処理を理解する必要があります。 throwsキーワードを挿入する場合は、do-catchtry?try!を使用するか、それを伝播する必要があります。だから、エラーがスローされた場合に起こることは、呼び出し側の責任です。ここで

は例です:あなたはifに達すると終了する場合error handling

ため

do { 
    try doSomething(foo) 
} catch arrayErrors.empty { 
    fatalError("Array is empty!") 
} 

Appleのドキュメント、単にエラー処理を使用している場合の内側fatalErrorを呼び出すことはありません。

if myArray.count = 0 { 
    fatalError("Error happened") 
} 
1

エラーが発生すると関数は戻ります。これをプレイグラウンドでポップし、出力を見てください。

//: Playground - noun: a place where people can play 

enum MyError: Error { 
    case emptyArray 
} 

func doSomething<T>(_ array: [T]) throws -> T { 
    guard !array.isEmpty else { 
     throw MyError.emptyArray 
    } 

    return array[0] 
} 

do { 
    let emptyArray: [Int] = [] 
    let x = try doSomething(emptyArray) 
    print("x from emptyArray is \(x)") 
} catch { 
    print("error calling doSeomthing on emptyArray: \(error)") 
} 

do { 
    let populatedArray = [1] 
    let x = try doSomething(populatedArray) 
    print("x from populatedArray is \(x)") 
} catch { 
    print("error calling doSeomthing on emptyArray: \(error)") 
} 

あなたは出力が表示されますが、それが呼ばれなかったので、throwは、その関数の実行を終了するので、あなたは、print("x from emptyArray is \(x)")からの出力が表示されない

error calling doSeomthing on emptyArray: emptyArray 
x from populatedArray is 1 

注意です。また、guardステートメントが関数の終了を要求するので、これを確認することもできます。

また、配列の最初のものを使用する場合は、T?を返すmyArray.firstを使用して、エラーを処理する代わりにnilのケースを処理できます。

//: Playground - noun: a place where people can play 

let myArray = [1, 2, 3] 

if let firstItem = myArray.first { 
    print("the first item in myArray is \(firstItem)") 
} else { 
    print("myArray is empty") 
} 

let myEmptyArray: [Int] = [] 

if let firstItem = myEmptyArray.first { 
    print("the first item in myEmptyArray is \(firstItem)") 
} else { 
    print("myEmptyArray is empty") 
} 

出力:たとえば

the first item in myArray is 1 
myEmptyArray is empty 
関連する問題