1

How to use 'guard' in swift.I have gone through many articles about 'guard'.But i didnt get clear idea about this.Please give me clear idea.Please give me sample output for following 'if' statement.

if firstName != "" 
{
   if lastName != "" 
   {
      if address != "" 
      {
        // do great code
      }
   }
 }
David Snabel
  • 9,801
  • 6
  • 21
  • 29
Madhumitha
  • 3,794
  • 8
  • 30
  • 45

4 Answers4

6

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"))

Output:

This will always be returned if data isn't nil
Data is "ok"

A bit more towards your question:

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
Eendje
  • 8,815
  • 1
  • 29
  • 31
3

you can use guard as well and your code will be more readable

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
 */
user3441734
  • 16,722
  • 2
  • 40
  • 59
1
  1. The purpose of guard is to validate some condition, and force a stop to execution if that condition is not met but defer defines a block of code that is not executed until execution is just about to leave the current scope.

  2. In guard, once the optional is unwrapped successfully, the unwrapped value can be used by subsequent code while Defer is useful for performing unconditional clean-up, whether or not some operation succeeds or fails.

  3. Guards provide an alternative to deeply nested if-let while defer provide an alternative of try/finally done right.

  4. Both are used for Control Flow and Error Handling

Usage guard & defer:

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”)
}

Please have a look http://nstechstack.com/archives/question/223-1

Max
  • 1,070
  • 3
  • 13
  • 19
app_rocker
  • 22
  • 2
0

Lets go through very simple if approach.

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()

Now Lets come to guard approach

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()
Tunvir Rahman Tusher
  • 6,421
  • 2
  • 37
  • 32