Tuesday, August 23, 2016

Using Guard for null check in Swift





Coming straight to the point. Guard improves readability. An hour back I was struggling why my nil check is not working as it is supposed to work. 

I wrote it something like this in my function. 


func setXYX -> Void{

     if (a != nil) {
        return;
    }
   
    if ( b != nil) {
        return;
    }

    print (" a and b is not null");
}

But even if both a and b is null, the print function is getting executed. Then I looked around for ways to do null check in swift.

I modified the above function to be like this

func setXYX -> Void{

     guard a != nil  else {
        return;
    }
   
    guard  b != nil else {
        return;
    }

    print (" a and b is not null");
}

Thats as simple as it can be.

The other good thing about using guard is about the scope of the variable. After the guard, the scope of the variable is still valid. You can print value of a and b if they are not nil.


I am using the guard for the first time and I by mistake used the let keyword. The error, "Variable binding in a condition requires an initializer" is really misleading to me. But here it is so that someone else wont make the same mistake.

func setXYX -> Void{

     // Compile time error
     guard let a != nil  else {
        return;
    }

     // Compile time error    
    guard  let b != nil else {
        return;
    }

    print (" a and b is not null");
}









No comments:

Post a Comment