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 Playlist Browser with Swift Refactoring Our Code Determining Playlists Programmatically

Jonathan Meier
Jonathan Meier
1,623 Points

I still don't get the difference between ! and ? after a declared variable/constant.

How can

@IBOutlet weak var playlistImageView0: UIImageView!

be equal to nil?

2 Answers

Ryan Jin
Ryan Jin
15,337 Points

Extremely rarely, some part of your code, or the compiler, or the iOS software might go wrong, and the UI is not connected to your code. Your app can crash since it is an force-unwrapped optional. Another reason is that sometimes you might forget to connect your code to the UI. It happened to me before when I just typed @IBOutlet var mLabel: UILabel! in ViewController.swift, and I forgot to connect that to the UI in main.storyboard, so then my app crashed since the UI doesn't exist but I force unwrapped it. But if you connect the UI to the code using control + drag, it shouldn't go wrong unless there are bugs in either your compiler, or the simulator, but anyway, 99.99% of the time, it won't happen.

Jonathan Meier
Jonathan Meier
1,623 Points

Ah I see - if I would connect it without the immediate unwrapping I wouldn't know if the UI is connected or not. Is this interpretation right?

What still is not 100%clear to me:

This:

var optionalVar: String!

is an optional which will be unwrapped automatically if used. On the other hand this:

var optionalVar: String?

does have to be chcked if nil or not.

Have I got that right?

THX a lot.

Ryan Jin
Ryan Jin
15,337 Points

You are right. If you add a "!" to the end of your data type, it will be automatically unwrapped, but if the value is nill, and you force unwrap it, it will crash. For example

var exclString: String!
let optionalString: String? = "Hello World" // optional(Hello World)
exclString = optionalString
println(exclString) // Hello World
exclString = nil
let newString: String = exclString // Crash when running the program but no error when debugging. Find nill when unwrapping