【发布时间】:2017-11-12 16:51:31
【问题描述】:
return 可以退出当前函数的作用域,但是否也可以退出调用内部函数的外部函数作用域?
func innerFunction() {
guard 1 == 2 else {
// exit scope of innerFunction and outerFunction
}
}
func outerFunction() {
innerFunction()
print("should be unreachable")
}
可能有一种方法使用我们可以检查的内部函数的返回值:
func innerFunction() -> Bool {
guard 1 == 2 else {
return false
}
return true
}
func outerFunction() {
guard innerFunction() else {
return
}
print("should be unreachable")
}
这种方法的问题在于,如果函数变得更加复杂并且您必须一遍又一遍地使用它们,它会很快使您的代码变得混乱。
考虑将此方法应用于XCTest。它看起来像这样:
func testFoobar() {
guard let unwrappedObject = helperFunction() else {
XCTFail("A failure message that can change with each helperFunction call")
return
}
print("should be unreachable when helperFunction already failed")
}
我想要类似的东西:
func testFoobar() {
let unwrappedObject = helperFunction()
print("should be unreachable when helperFunction already failed")
}
【问题讨论】: