作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
如何在 swift 中使用“守卫”。我已经阅读了很多关于“守卫”的文章。但是我对此没有清楚的了解。请给我明确的想法。请给我以下“if”语句的示例输出。
if firstName != ""
{
if lastName != ""
{
if address != ""
{
// do great code
}
}
}
最佳答案
A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
func doSomething(data: String?) -> String {
// If data is nil, then return
guard let data = data else { return "Invalid data" }
defer { print("This will always be printed if data isn't nil") }
// data is now a non optional String
if data.lowercaseString == "ok" { return "Data is \"ok\"" }
return "I'm your father"
}
print(doSomething("ok"))
输出:
This will always be returned if data isn't nil
Data is "ok"
更多关于你的问题:
The value of any condition in a guard statement must have a type that conforms to the BooleanType protocol.
func doSomething(data: String) -> String {
guard !data.isEmpty else { return "Data is empty" }
return data
}
print(doSomething("ok")) // ok
print(doSomething("")) // Data is empty
关于swift - 如何在 swift 中使用 guard 而不是 if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36370513/
我是一名优秀的程序员,十分优秀!