swift - 如何在 swift 中使用 guard 而不是 if

标签 swift if-statement swift2 guard-statement

如何在 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/

相关文章:

ios - 为测试定义常量值,为调试定义另一个常量值

ios - 从 Storyboard 设置 IBAction 时获取 'Touch Drag Inside' 距离

ios - fatal error : unexpectedly found nil while unwrapping an Optional values

bash - 将管道输出传递给测试命令

java - If ... Else 语句似乎返回错误的输出

swift - Spritekit 中的 Pan Gesture Recognizer 移动对象

ios - 避免在 ReactiveCocoa 上重复 http 请求

iOS+ swift : Why is music not played on iPad?

ios - swift5关闭页面时如何传递参数?

python-3.x - 能够访问一个 if 语句中的变量,但不能访问其他语句