如果不让-在Swift中 [英] If not let - in Swift
问题描述
有没有一种方法可以迅速消除"if let"? 在我看来这很愚蠢:
is there is a way to negate the "if let" in swift? This looks silly to me:
if let type = json.type {
} else {
XCTFail("There is no type in the root element")
}
我不能使用XCTAssertNotNil,因为json.type是一个枚举.
I can't use XCTAssertNotNil, because json.type is a enum.
enum JSONDataTypes {
case Object
case Array
case Number
case String
}
非常感谢
它是:
var type: JSONDataTypes? = nil
推荐答案
Swift 2.0(Xcode 7)和更高版本具有新的guard
语句,该语句的工作方式类似于"if let let"(您可以有条件地绑定)封闭范围的其余部分中的一个变量,以使代码中的良好路径"缩进最少.
Swift 2.0 (Xcode 7) and later have the new guard
statement, which sort of works like an "if not let" -- you can conditionally bind a variable in the remainder of the enclosing scope, keeping the "good path" in your code the least-indented.
guard let type = json.type else {
XCTFail("There is no type in the root element")
}
// do something with `type` here
要注意的是,guard
的else
子句必须退出该范围(因为否则,您将陷入该子句之后的代码中,其中不受约束的变量(如上述type
)是未绑定的) .因此,它必须以return
,break
,continue
之类的东西结尾,或者以编译器已知的永不返回的函数结尾(即带有注释的@noreturn
,例如abort()
...),我不记得了.如果其中包含XCTFail
,则立即使用,但应该(提交错误,如果不包含).
The catch to this is that the else
clause of a guard
must exit that scope (because otherwise you'd fall into code after that clause, where the guarded variables, like type
above, are unbound). So it has to end with something like return
, break
, continue
or a function that is known to the compiler to never return (i.e. annotated @noreturn
, like abort()
... I don't recall offhand if that includes XCTFail
, but it should (file a bug if it's not).
For details, see Early Exit in The Swift Programming Language.
对于真正古老的东西... Swift 1.x中没有否定形式的if-let.但是由于无论如何您都在使用XCTest,因此只需测试断言表达式的可选部分即可:
As for really-old stuff... There's no negated form of if-let in Swift 1.x. But since you're working with XCTest anyway, you can just make testing the optional part of an assertion expression:
XCTAssert(json.type != nil, "There is no type in the root element")
这篇关于如果不让-在Swift中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!