Migrating ifs to guards in Swift
ericasadun.com
ericasadun.com
@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.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.
The customary way of saying that is “unwrapping optional arguments”.
Takes this to another degree for .Net. Enables deeper static analysis to catch more programming errors before runtime.
"guard let x = x where x > 0 else {}" first unwraps the optional (check if it is not nil), then it checks if the value is greater than 0.
This is the nice thing about "guard let ...". Below the guard statement, x is no longer an optional.
https://dlang.org/spec/contracts.html http://docs.racket-lang.org/guide/contracts.html
and here's a library to add it to ruby (i've seen a couple of others floating around): https://egonschiele.github.io/contracts.ruby/
I would love to see something like LINQ make it into Swift.
When a giant like Apple gives itself a clean slate to work on designing a new language, it's die-hard fans deserve better than the rag tag mess the OP has to get into and yet can't help but simply be satisfied with respect to what he had to deal with before.
And nobody but insecure people give a crap. The rest of us just want to use good tools to get our jobs done.
On one hand, we can choose a younger, less-mature language/platform like Swift. On the other, we can choose C# and .NET, even if we're not targeting Windows, and get a very mature and capable language with a superb standard library, and a very large existing user community.
Whether they like it or not, Swift and its community will have to compete with what .NET offers. As it currently stands, Swift is likely on the losing end of many of these competitions in many cases. Will this change in the future? Perhaps. But it will take a lot of effort from the Swift team and its supporters.
One area Apple has a huge leg up is its API design. All of Apple's frameworks are well thought out and easy to use. Microsoft, not so much. One glaring example is Bluetooth: CoreBluetooth is a straightforward abstraction, whereas Microsoft's is a total Frankenstein shit show.