I try to get to grips with Swift and how to best separate nil and valid objects from optionals.
I have this code:
var my AwesomeDict = [:]()
...
... (myAwesomeDict gets populated)
...
let myOptionalObject:objectClass? = myAwesomeDict[key]
if let myUnwrappedObject = myOptionalObject {
...
} else {
println("Sorry, object is nil")
}
When I put brackets around the if clause (I feel it improves readability), XCode will flag the line with a compiler error:
Pattern variable binding cannot appear in an expression
What is different about
if (let myUnwrappedObject = myOptionalObject) {
from
if let myUnwrappedObject = myOptionalObject {
? Sadly, the documentation makes no mention of the effect of braces around if conditions. It seems I need to use the bracket-free version, but would like to become more enlightened about the reason.
Well here, if let
is a pattern itself. So if you put a bracket between the if and let, you break the pattern.
If you do that, Swift thinks that you want to check the let
itself.
So simply said: If you use if let
don't use brackets, because it breaks the if let
pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With