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

Johan Jensen jj at johanjensen.dk
Wed Jan 6 04:49:33 CST 2016


On Wed, Jan 6, 2016 at 11:09 AM, James Campbell via swift-evolution <
swift-evolution at swift.org> wrote:

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

But it’s not.
guard’s else-clause requires you to transfer program control outside the
guard statement’s enclosing scope.
And any constants or variables assigned a value from an optional binding
declaration in a guard statement condition can be used for the rest of the
guard statement’s enclosing scope. That is what allows us to do `guard let
val = opt else { return }` where opt is an optional and val is the value
contained in opt if it is not nil.

Changing it to unless (and removing the else-clause) would only confuse
people coming from Ruby or similar languages, as they wouldn’t expect any
of the variable declarations to live in the guard statement’s enclosing
scope.


>
> So in other languages what have they called this, well in Ruby they called
> it "unless" which I feel is a much clearer form of intent and lower barrier
> of entry for a user. See this code.
>
> guard name != nil else {
>    fatalError("Please enter a name")
> }
>
> What does that actually say if you look at it from a linguistic point of
> view, "guard that name doesn't equal nil otherwise fail", that feels very
> obtuse.
>
> With my proposal the syntax could become this:
>
> unless name != nil {
>   fatalError("Please enter a name")
> }
>
> This now reads as "unless name doesn't equal nil then fail" which I think
> is a much clearer syntax. I think this would be a great change for Swift 3.
> For me I think this is more friendly for beginners.
>
> It would support the same structure as an if block:
>
> unless name != nil {
> }
> else
> {
> }
>
> Going forward it would allow us to be more flexible if we added inline
> if/unless statement, as in Ruby.
>
> callThisMethod() if age > 0
> throwThisError() unless age <= 0
>
> --
>  Wizard
> james at supmenow.com
> +44 7523 279 698
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160106/b6b63573/attachment.html>


More information about the swift-evolution mailing list