3 ms·
I've recently started writing code (for an OS X app) in Swift, and I find the guard statement truly fantastic. Many of my methods do very little except test for
by jakobegger 11y ago
I've recently started writing code (for an OS X app) in Swift, and I find the guard statement truly fantastic. Many of my methods do very little except test for preconditions, and the "guard" statement makes this very clear. For example, my action methods all look like this:
@IBAction func doSomething( sender: AnyObject ) {
guard ... else { NSBeep(); return }
guard ... else { NSBeep(); return }
guard ... else { NSBeep(); return }
mutateState()
}
There's now a clear separation between the part that just checks preconditions, and the part that does something. It's really nice for defensive programming, and makes it easy to write programs that do not crash.
- seivan 11y agoYeah, guard is awesome, especially for making arguments from optionals to regular(?) variables. But you kinda had that "guard" with NSAssert() in DEBUG. In fact all methods should have NSParameterAssert() for mandatory arguments before recent Obj-C additions. You could written your own assertion to work in production and do a beep and return.
- Aleman360 11y agohttps://github.com/Microsoft/CodeContracts https://github.com/Microsoft/CodeContracts Takes this to another degree for .Net. Enables deeper static analysis to catch more programming errors before runtime.