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 Enumerations and Optionals in Swift Objects and Optionals Optional Chaining

Using 'guard' instead of 'if let'

I wanted to try out using 'guard' instead of 'if let' in the example on line 33 given by Pasan:

guard let buildingNumber = susan.residence?.address?.buildingNumber else { return nil }

print(buildingNumber)

I got the following error: Return invalid outside of a func.

Can someone please elaborate as to why this doesn't work? Can I only use guard statements inside methods?

Many thanks

1 Answer

Abdullah Althobetey
Abdullah Althobetey
18,216 Points

Hi Sam, You can use guard statements inside and outside methods, but you can 'return' only inside methods. I believe you entered this code inside a playground, so you can, for example, print an error message instead of return nil, or you may use the fatalError() function if you want to stop program execution. Hope this help.

Thank you Abduallah for your quick response. I haven't studied fatalError() yet but tried it out and worked for me. Thanks very much!