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

How to use guard in swift instead of if

如何在swift.I中使用'guard'已经看了很多关于'guard'的文章。但是我没有弄清楚this.Please给我清楚的idea.Please 给我以下 '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

你也可以使用 guard,你的代码会更易读

let firstName = "First"
let lastName = "Last"
let address = "" // empty

if firstName != ""
{
    if lastName != ""
    {
        if address != ""
        {
            print(1,firstName,lastName, address)
        } else {
            print(1,"address is empty")
        }
    } else {
        print(1,"lastName is empty")
    }
} else {
    print(1,"firstName is empty")
}

func foo(firstName: String, lastName: String, address: String) {
    guard !firstName.isEmpty else { print(2,"firstName is empty"); return }
    guard !lastName.isEmpty else { print(2,"lastName is empty"); return }
    guard !address.isEmpty else { print(2,"address is empty"); return }

    print(2,firstName,lastName, address)
}

foo(firstName, lastName: lastName, address: address)
/*
 1 address is empty
 2 address is empty
 */
foo(firstName, lastName: lastName, address: "Address")
/*
 2 First Last Address
 */
  1. guard的目的是验证某些条件,如果不满足该条件则强制停止执行但是defer定义了一段直到执行即将离开才执行的代码块当前范围。

  2. 在 guard 中,一旦 optional 被成功解包,解包后的值可以被后续代码使用,而 Defer 用于执行无条件清理,无论某些操作是否成功。

  3. Guards 提供了深度嵌套 if-let 的替代方案,而 defer 提供了 try/finally 正确完成的替代方案。

  4. 两者都用于控制流和错误处理

使用保护和延迟:

for imageName in imageNamesList {
    guard let image = UIImage(named: imageName)
else { continue }
    // do something with image
}

func deferExample() {
    defer {
        print(“This will be run last”)
    }
    defer {
         print(“This will be run second-last”)
    }
    print(“operation started”)
    // …
    print(“operation complete”)
}

请看http://nstechstack.com/archives/question/223-1

让我们通过非常简单的 if 方法。

class MySampleClass {

    var sampleString:String?

    func printSampleString() -> Void {


        if let str = sampleString{ ///if sampleString is nil the if will escape

            print(str) ///sampleString is not nil
        }
    }
}

var obj : MySampleClass = MySampleClass()
obj.sampleString = "SampleString"///Assign value to sampleString
obj.printSampleString()

现在让我们来guard方法

class MySampleClass {

    var sampleString:String?

    func printSampleString() -> Void {


        guard let str = sampleString else { ///guard will ensure sampleString is not nil

            return ///if sampleString is nil,then return
        }

        print(str) //sampleString is not nil,so print str!

    }
}

var obj : MySampleClass = MySampleClass()
obj.sampleString = "SampleString"///Assign value to sampleString
obj.printSampleString()