エラーが発生すると関数は戻ります。これをプレイグラウンドでポップし、出力を見てください。
//: 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
あなたは、 "空の配列を返す" とはどういう意味ですか?あなたの関数は 'Int'を返します。 – Hamish
あなたがあなたの質問にした陳述は真実ではなく、ほとんどのものはほとんど意味がありません。 * "配列が0のとき*"と言うとき、実際には "配列が空のとき"を意味しますか?また、 "throw"行が実際に呼び出された場合、 'return'行には続かず、何も返されません。 – rmaddy