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 Building the Master and Detail Views Displaying Playlist Information

Hamid Hadi
PLUS
Hamid Hadi
Courses Plus Student 7,297 Points

Use playlist !.[property] instead of playlist?.[property]

When you wanted to grab playlist properties You use "playlist !. [property]" and did not use playlist ?.[property]". Can you tell me the difference between them?

1 Answer

Sam Chaudry
Sam Chaudry
25,519 Points

! ? are both used in Swift as optionals. Most of the time when you make a API call i.e. get some data from the internet you are taking that data and unwrapping it into a data type.

So for example you get some data back about the weather in a city and you want to display the city name:

{ City : "London" }

We could take this data and create the following variable and pass the value into it:

var city:String! = "London";

-> Here we have a variable which is expecting to be a String, the use of ! in simple terms say the value of this variable will explicitly be a String. However the catch is that in some instance if you didn't get a String this due to a data error and instead you got nothing back, it would stop working because it is expecting a String as this data type. So to fix this and prevent a programme melt down you could do:

var city:String? = "London"

-> The ? is saying I may get a String but if it is nil we can still run the programme.

var Latitude: double? = 55.34;

-> Here we could get a double but hey of I get nothing back we can still run the programme.

Working with Swift what you will find is that we tend to use ? and ! a lot to check so worth spending some time on it.

O Or
O Or
2,761 Points

Hi Sam, This is an awesome explanation. However in the detailViewController he unwraps the Title this way

<p> playlistTitle.text = playlist!.title </p> 

Why doesnt he unwrap the title property as well, since it too is an optional? i.e

<p> playlistTitle.text = playlist!.title! </p>

I tried it and it worked but i would like to know how optional unwrapping works with properties