Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Vending Machine App in Swift 2.0 Loading Data From a Resource Inventory Errors

Timothy Kaye
Timothy Kaye
2,765 Points

How to know when an Error will arise?

Hi, I am watching this video and it mentions that we need to 'guard' against errors which we 'throw'. I am wondering how we are to know when to 'guard' against an error..?

Many thanks in advance.

Greg Kaleka
Greg Kaleka
39,021 Points

Hey Timothy,

Gavin mentions the Optionals course below. You should absolutely watch it and the Error Handling course before you continue in this course. Essential content you need to know to get the most out of this course.

2 Answers

Take a look at the videos covering "Optionals". Again, a very powerful concept - possibly one of the best in Swift. I can't really do them justice here in a few lines, but an optional is a way of indicating that a variable can not only contain a value (e.g. an integer with a value of 5), but can potentially also contain a non-value (i.e. nil). Optionals allow Swift to check for common runtime errors at compile time - so you get to fix the issues before your customer ever sees them! That probably makes little sense, but go read up on Optionals and you'll soon understand how powerful they are.

Timothy Kaye
Timothy Kaye
2,765 Points

Thanks Gavin. Greatly appreciated!

I've not watched that particular video, but the guard keyword is very useful as it allows you to avoid what Apple call the Pyramid of Doom where you have lots of nested if let checks trying to unwrap optionals and weed out what conditions might cause you grief. Guard flips everything around from checking for what might be wrong, with asserting what you need to be true. With the guard keyword you state the conditions required in order to continue, and if they aren't met guards else block is executed where you would typically return back to the calling function with an error condition, throw an error (via throw statement) or perform something blunt like calling fatalAlert(). It's a simple concept, and in trivial examples you don't see the full power of it, but in a non-trivial codebase it's a wonderful construct and one which developers should definitely look to taking advantage of.

Timothy Kaye
Timothy Kaye
2,765 Points

Gavin, many thanks for your comments. Makes a lot of sense.

One last thing... exactly what does 'unwrap' mean?