But this would then go when all I really want is the not part if let twinkling = getHighGem() as? MyGem { } else { ..... }
Sorry, I wanted the NOT (!) equivalent to : if let twinkling = getHighGem() as? MyGem
I cannot be sure if I would be interpreting what you mean correctly, but you want to find some sort of better alternative for this?
if let twinkling = getHighGem() as? MyGem { /* Do nothing */ } else {
.....
}
As this type of code:
if someCondition { /* Do nothing */ } else {
.....
}
can be re-written using not !
operator:
if !someCondition {
.....
}
If you want to do something like above, you need to think what if-else would do on true-case and false-case:
The if-let first checks the Optional value of the right hand side if it is nil or not:
- And if it is not nil, it does a little more
- Unwrap the Optional value and retrieve the non-Optional value
- Create a new binding to the unwrapped value as a local constant
- Execute the true-case code block
- And if the checked value is nil
- Execute the false-case code block
So, if you just want a false-case execution, you just need a nil checking:
if (getHighGem() as? MyGem) == nil {
.....
}
In this case, it can be rewritten as:
if !(getHighGem() is MyGem) {
.....
}
But, as you can see in the answer of Graphics and Games Engineer, using guard-let-else would be a better alternative in various cases. If you had shown enough context, you would have been shown which is better.