Monday, April 4, 2016

Overview

The new guard keyword allows us to solve one of the most important parts of coding: preconditions. Its addition to the Swift language was welcomed with open arms. I’ll explain how it works in this post and you’ll quickly understand why it’s so great.

Content

If you have a method that takes in an Optional (could be null), you would make sure that it’s a valid parameter at the beginning of the method.

1
2
3
4
5
6
7
8
9
func doSomething(anInt: Int?) {
  if anInt == nil || anInt! > 50 {
    // anInt is not valid, don't go further
    return;
  }

  // anInt is good, continue with the method
  anInt!.description
}

This is ok, but Swift has the let keyword that unwraps the Optional.

1
2
3
4
5
6
7
8
func doSomething(anInt: Int?) {
  if let anInt = anInt where anInt > 50 {
    // anInt is good, continue with the method
    anInt.description
  }

  // anInt is not valid, don't go further
}

This is a problem, because now we have the possibility of creating a pyramid of doom. So, the guard keyword was introduced.

1
2
3
4
5
6
7
8
9
func doSomething(anInt: Int?) {
  guard if let anInt = anInt where anInt > 50 else {
    // anInt is not valid, don't go further
    return;
  }

  // anInt is good, continue with the method
  anInt.description  
}

Random Posts