我已经用下面的函数抛出不退出功能:功能的投用执行特罗
func doSomething(_ myArray: [Int]) throws -> Int {
if myArray.count == 0 {
throw arrayErrors.empty
}
return myArray[0]
}
但是,当阵列等于0,它会抛出错误,但它会继续执行功能返回空数组。
如何在转到if语句时退出函数?
我已经用下面的函数抛出不退出功能:功能的投用执行特罗
func doSomething(_ myArray: [Int]) throws -> Int {
if myArray.count == 0 {
throw arrayErrors.empty
}
return myArray[0]
}
但是,当阵列等于0,它会抛出错误,但它会继续执行功能返回空数组。
如何在转到if语句时退出函数?
您需要了解错误处理。如果您插入throws
关键字,任何调用它的人都需要使用do-catch
语句,try?
,try!
或继续传播它们。那么如果错误发生将会发生什么取决于调用者。
下面是一个例子:
do {
try doSomething(foo)
} catch arrayErrors.empty {
fatalError("Array is empty!")
}
如果你想退出,一旦你到达if
,根本就没有使用错误处理和呼叫fatalError
的,如果里面的文件。
if myArray.count = 0 {
fatalError("Error happened")
}
该函数在您抛出错误时会返回。在操场上弹出并观察输出。
//: 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)")
}
你会看到输出
error calling doSeomthing on emptyArray: emptyArray
x from populatedArray is 1
请注意,您没有看到输出print("x from emptyArray is \(x)")
,因为它从来没有所谓,因为throw
结束该功能的执行。您也可以确认这一点,因为guard
语句需要退出该功能。另外,要注意的是,如果你想从数组中获得第一个东西,你可以使用myArray.first
,这将返回T?
,你可以处理这个零案例,而不必处理一个错误。例如:
//: 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