Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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