[swift-evolution] More flexible guard statement

Arthur Sabintsev arthur at sabintsev.com
Sat Dec 12 12:02:53 CST 2015


Not 100% a fan of this idea. 

There’s a parallel thread going on right now about adding unless/until into the stdlib. I think that’s what you may want.

As for mixing guard and where, you can do that already.

Here’s a contrived example:

import UIKit

var a: UIView?
var b: UIView?

func contrivedExampleFunc() {

    guard let a = a as? UILabel where a.backgroundColor == .blackColor(),
        let b = b as? UIButton where b.backgroundColor == .whiteColor() else {
            return
    }

}


Best,

Arthur / Sabintsev.com

On December 12, 2015 at 12:43:20 PM, Jakob Egger via swift-evolution (swift-evolution at swift.org) wrote:

At the moment "guard let" can only be used for unwrapping optionals. It
would be really nice if it could also be used with non-optional values.
For example, I'd like to write code like the following

guard  
let tableView = self.tableView,
let col = tableView.columnWithIdentifier("MyColumn") where col != -1
else {
NSBeep()
print("an error occurred")
return
}

This is not possible, because the second let assignment is non-optional,
so I have to write it like this:

guard let tableView = self.tableView else {
NSBeep()
print("an error occurred")
return
}
let col = tableView.columnWithIdentifier("MyColumn")
guard col != -1 else {
NSBeep()
print("an error occurred")
return
}

This leads to a lot of duplicated error handling code.

Ideally, I'd also like to mix let & where clauses in a single guard
statement, like this:

guard  
let tableView = self.tableView,
let col = tableView.columnWithIdentifier("MyColumn") where col !=
-1,
let headerCell = tableView.tableColumns[col].headerCell as?
MyTableHeaderCell
else {
NSBeep()
print("an error occurred")
return
}

What do you think? Right now I always end up writing a lot of separate
guard statement, and I have a lot of repeated error handling code.


Best regards,
Jakob
_______________________________________________
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/20151212/422671a7/attachment.html>


More information about the swift-evolution mailing list