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

HaeJu Lee
HaeJu Lee
3,811 Points

Question About findApt(“101”)?.toInt() and ? mark for optionals

1) Why should I write a code like findApt(“101”)?.toInt() ? Does ?. in findApt(“101”)?.toInt() mean something meaningful, or ?. is just a syntax(grammar) for synthesizing 2 lines of code to one? (?. is just a systax for optional chainging, and I don't have to think about its meaning deeply?)

2) I only saw ? used when clarifying type of a variable or constant, for example, var index: Int? = 3. Can I see any other applications of ? for optionals, except findApt(“101”)?.toInt() ?

My question is a bit long. Thanks for reading :)

3 Answers

Hello HaeJu Lee :

What you are doing with findApt(“101”)?.toInt() is making it an optional. For example..

I’m assuming that findApt() is a function that iterates through some apartment numbers, and if it finds it then it will do something with it. But what if there is no apartment 101 ? it will return nil because it’s an optional. The toint() is converting the string “101” to an Int. Meaning from text to a number, and its doing it by means of casting.

Hope it helps you understand a bit more.

the ? mark means it is an optional, You use optionals in situations where a value may be absent, so the value could be nil or the type you are referring to, if the value you are intending to retrieve fails, it returns nil, that's why you want to use optional chaining(if let =findApt(“101”)?.toInt(){} ), to prevent your app from crashing if the variable's or constant's value happens to be nil.

I'm new to Swift and Optional seems a bit confusing to me. Am I wrong or another way to get the same result would be to compare the "let constant" against a nil result and then use ! to get the "non optional" value (if it exists)?

i come from other languages and the "optional thing" appears not so much convenient... is an idea that will disappear as I go more in the code?

(sorry for bad english)