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 Enums and Structs Enums Associated Values

Gregory Millan
Gregory Millan
3,719 Points

Optional question from quiz

How is the following question's answer an optional and not an Int?

What is the data type of the constant today? let today = Day(rawValue: 1)

3 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Gregory Millan,

In this example code, the type of the constant "today" will be Day?. Let me explain the reasoning behind this.

Take a look at the following code:

let today = Day(rawValue: 1)

We are initializing the value for today by using a raw value. This raw value will assign the enum member of Day that it corresponds to, to the constant today. However, its possible try and initialize a type of Day by using an invalid raw value. For example, if our enum only had 7 members - the 7 days in the week, and we tried to initialize with a raw value of 8, the raw value initialization would fail. This is what makes this method of initialization, from a raw value, known as a failable initializer and it is the reason why today is of type Day?. Initializing from a raw value ALWAYS returns an optional type whether it succeeds or fails, as a safety feature.

Hope this helps, good luck!

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,624 Points

Hey Gregory,

This is returning an optional because it's not sure if the raw value exists. When you do that line of code, it is not returning the int that is passed in as the raw value, but rather the value that is assigned to the raw value. It has to return an optional in case the raw value passed in has not been assigned to a specific value.

Amit covers this in this video starting at the 6:00 mark. You may want to review this part of the video and how raw values work in Swift.

Keep Coding! :dizzy:

Gregory Millan
Gregory Millan
3,719 Points

Thanks Jason & Steven!

I got it now!