swift

Using guard to test for an empty string

In Swift, we have a syntax candy called 'guard'..

Using guard to test for an empty string

The code to check and bail out if a string is NULL or empty most of the time looks something like that:

if self.text == nil || self.text!.isEmpty  {
    return
}

In Swift, we have a syntax candy called guard that executes statements based on a Boolean value of an expression. With guard in mind we can re-write the code above:

guard let gText = self.text where !gText.isEmpty else {
    return
}

Of course the question is whether using guard makes the code cleaner or more confusing.

It is up to you to decide!

Subscribe to The infinite monkey theorem

Get the latest posts delivered right to your inbox