gpt4 book ai didi

ios - Guard let Cause ,从整个功能 block 返回

转载 作者:行者123 更新时间:2023-11-30 13:58:16 25 4
gpt4 key购买 nike

以下代码从guard let details返回,但不执行其他打印语句。

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.

let testDictionary:[String:AnyObject] = ["a":NSMutableArray()]

let result = testDictionary["C"]

print("Before details Check")
guard let details = result where details.isKindOfClass(NSArray) else {
return false
}
print("Returned Result \(details)")
print("After Details Check")
return true
}

gaurd后面的语句没有被执行有什么原因吗?我做错了什么?

最佳答案

来自"Statements"在 Swift 文档中:

Return Statement

A return statement occurs in the body of a function or method definition and causes program execution to return to the calling function or method.

Guard Statement

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
...
The else clause of a guard statement is required, and must either call a function marked with the noreturn attribute or transfer program control outside the guard statement’s enclosing scope ...

如果您的 guard let details = 条件失败,则返回“立即”从当前函数返回。你不能简单地继续,因为 details 将是未定义的。正是如此guard 语句是为之而创建的。

您可以通过引入本地范围来解决您的问题:

print("Before details Check")
checkLabel: do {
guard let details = result where details.isKindOfClass(NSArray) else {
break checkLabel
}
print("Returned Result \(details)")
}
print("After details Check")

这里,break checkLabeldo-scope 之后继续执行 if条件失败。

但更简单的方法是使用 if-let 而不是 guard-let:

print("Before details Check")
if let details = result where details.isKindOfClass(NSArray) {
print("Returned Result \(details)")
}
print("After details Check")

关于ios - Guard let Cause ,从整个功能 block 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33325286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com