[swift-evolution] Rename "guard" to "unless"

Scott Matthewman scott at matthewman.net
Wed Jan 6 04:46:53 CST 2016


> What is "guard"? why its the opposite to "if"!

Not exactly. It’s a guard clause, designed to be used at the beginning of a
method to ensure that certain conditions exist, and to exit early if they
do not.

In addition, guard in Swift works different to if in that any `let`
declarations made within the guard clause are set within the scope of the
parent method – especially useful if you need to unwrap optionals. With if,
they are only valid within the if block.

For example:

    if let name = optionalName as? Name {
      print(name) // okay
    }

    print(name) // out of scope

But with guard:

func printName(optionalName: Name?) {
  guard let name = optionalName else { return }

  print(name) // this is okay
}

So yes, the distinction is subtle – and in Ruby (the language I use in my
day to day work) we implement guard clauses with ‘if' or ‘unless’ blocks or
modifiers.

But with the difference in scope of assigned variables between `if` and
`guard` in Swift, I think your suggestion would make things slightly more
confusing, instead of slightly less.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160106/c1f3e7f7/attachment.html>


More information about the swift-evolution mailing list