Hey everyone! First post. I’m loving the instruction here. JUST FINISHED the iOS Foundations course ––WOOP WOOP!
I want to share something cool I [think] I’m figuring out –– the power of guard and guard-let!
In the City Sights App, we had a gazillion JSON keys to parse and we made them all optional. Sounds like a good call, but causes the annoyance of adding a gazillion+ unwrappings, with prolly a lot of if-let statements, and nested ones. Aye!
This causes at least 2 problems: 1) we have lots of indentation, and code gets harder to read, 2) we have a more limited scope to work with each of the things we’re if-letting. In other words, we can only access the if-let constants (and if-var variables, of course–yeah, you can do dat!) from within the scope of those if-lets / if-vars.
Enter the guard-let statement!
Say we have an optional
at Class.property
that we need to do something with. Instead of:
if let property = Class.property {
// do some stuff with safely unwrapped property
}
We can say:
guard let property = Class.property else { return }
// do some stuff with safely unwrapped property
See? The // do some stuff with
line of code is now outside of the scope of the handling of the optional (I’m forgetting the term for this kind of optional handling…).
Don’t forget––in either the if-let or guard-let, you can add multiple checks, like:
guard let error == nil, let response else { return }
// do some stuff with safely unwrapped response, knowing error == nil
…and like above, if you’re checking a local symbol (without a dot in the name), you don’t even need an equal sign. Also like above, you can mix conditional checks with lets or vars! This also applies to if-let / if-var.
You can’t use guard-let anywhere you use if-let, but a lot of places do work. For example, I haven’t been able to use guard statements at all in view structs. In the context of views, our options are if let
|| if var
|| ??
|| !
.
FUN!