Guard in Swift

Guard statement is similar to IF statement except the fact that body of code executes when the condition in guard statement is evaluated to false.

var citizenAge:Int  //Declare a variable of type Integer

citizenAge = 65

guard citizenAge < 60  else {
// Here citizen age is 65, the guard condition is evaluated to false and the below statement is executed.
print("Senior Citizen")
print("Not a Senior Citizen") // this is executed when guard condition is true.

Guard Statement can also be used for optional binding

var playerScore:Int?    //Declare a variable a of type Optional Integer, which might or might not have value (for e.g if player did not bat, he might not have any score)

func updatePlayerScore (playerScore:Int?){
    guard let score =  playerScore else {
        print(“Player did not bat“)
    print("Player score is \(score)")
  • Unlike if statement values assigned in the Guard statement are still available after the Guard statement through out the remaining scope that encloses the Guard Statement
  • Guard Statement are typically written at the top of the enclosing scope

No comments:

Post a Comment