Join Harrison Ferrone for an in-depth discussion in this video The guard statement and defensive programming, part of Learning Swift 3 for Developers.
- [Harrison] A lot of times, we're unwrapping optionals…as a way of determining…if we should proceed with an operation.…Like in the example use case I mentioned…where we want to check…that a user has a valid non-nil email and password.…Let's start with checking if a user exists.…I'm going to make myself some room…and add another header comment,…The Guard Statement and Defensive Programming.…We need three new variables here.…
Var userExists, this is going to be an optional bool,…and we're going to set it to true.…Next, we're going to have a variable called emailText.…This is going to be an optional string,…and it's going to have an empty value for now.…The third variable we want is passwordText,…which is also going to be an optional string…and have an empty value.…Now let's use the guard keyword.…Guard let.…
We're going to call this hasUser equals userExists,…else, we're going to print out, you shall not pass,…and we're going to use the fatal error method.…Now don't worry about that.…That's just to throw an error if the guard statement fails.…
- Starting a new playground
- Printing to the console
- Declaring variables
- Working with numbers
- Using strings
- Breaking down optionals
- Understanding closures
- Classes vs. structs
- Extensions and protocols
Skill Level Beginner
1. Hello Swift
2. Back to Basics: Variables and Operators
3. Collections, Tuples, and Enumerations
4. Working with Logic Flows
5. Only in Swift: Optionals
6. Functions, Closures, and Associated Types
7. Classes vs. Structs
8. Advanced Topics
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.