use*_*890 4 nsdictionary guard ios swift
如何在不中断循环的情况下在循环中执行多个guard语句?如果一个保护语句失败,它会将我踢出当前循环迭代并绕过剩余的代码.
for user in users {
guard let first = user["firstName"] as? String else {
print("first name has not been set")
continue
}
print(first)
guard let last = user["lastName"] as? String else {
print("last name has not been set")
continue
}
print(last)
guard let numbers = user["phoneNumbers"] as? NSArray else {
print("no phone numbers were found")
continue
}
print(numbers)
}
Run Code Online (Sandbox Code Playgroud)
如何确保为每个用户执行所有语句?在else块中放置return和break也不起作用.谢谢!
guard语句的目的是检查条件(或尝试解包一个可选项),如果该条件为false或选项为nil,则您要退出当前作用域.
想象一下,警卫声明(用甘道夫的声音说)"如果你不符合这个条件你就不会过去......"
你想在这里做什么可以简单地用if let语句完成:
for user in users {
if let first = user["firstName"] as? String {
print(first)
} else {
print("first name has not been set")
}
//Do the same for the other fields
}
Run Code Online (Sandbox Code Playgroud)
需要注意的一点是,guard letguard语句中允许您在guard语句之后访问未包装的值,因为if let只允许您在下一个块中访问该值.
| 归档时间: |
|
| 查看次数: |
438 次 |
| 最近记录: |