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 Swift Functions and Optionals Optionals Optional Chaining

Why is 2:51 unsafe with the bang unwrapping?

Amit mentioned that bang unwrapping is unsafe, and I could understand why cause we can never expect valuables to have a value, however, in 2:51, culprit has already did an optional checking in line 21. So if culprit.toInt()! in line 22 can be reached, it definitely has a value already, therefore being safe? No?

Would appreciate if someone can clear this up :)

Thanks in advance

2 Answers

In the case you described yes, it is safe to use force-unwrapping. It is not in all those situations where you don't first make sure (with optional binding, for example) that the value exists. If you wrote:

let culprit = findApt("102")

then you'd be writing unsafe code, because you didn't perform any sort of check before force-unwrapping.

Eduardo Calvachi
Eduardo Calvachi
6,049 Points

For Swift 2.1, since the optional was safely unwrapped and the value inside the conditional statement can be casted as an int:

if let culprit = findApt("104") {
        sendNoticeTo(apt: Int(culprit)!)