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 Enumerations and Optionals in Swift Objects and Optionals Pattern Matching With Enums

What is the role of = in this video?

The job that it seems to be doing is comparing case .nickel to coin, but the equal to comparison operator is == and not =. The only use of = that I am familiar with is as an assignment operator, and that is obviously not the case here.

In addition, what I don't understand about the "if case .some (let x) = someOptional" is somewhat related to this. First, what actually happens in the case that there is an associated value with the optional? I assume that it does not just iterate through every possible value with the correct type since that would take forever. Therefore, does this mean that the = actually is acting as an assignment operator here in the sense that it assigns the associated value of someOptional to x if it has a value?

1 Answer

Joseph Lucero
Joseph Lucero
2,891 Points

1) My understanding is that this is part of the "syntactical sugar" that cases provide in pattern matching. Instead of having to use the equality operator (==), when you use the syntax "case" you'll always(?) use just a single = to compare things.

https://stackoverflow.com/questions/27554153/error-why-matching-an-enumeration-using-a-if-statement

2) I'm not sure I understand the second part of your question completely, but my understanding is that this code (a) checks to make sure that someOptional is of case .some and, if so, (b) then assigns the value of x to whatever the associated value in the enum is. There is no need to iterate over every possible value, since this would be called on an instance of an enumeration so the enumeration must exist and then the compiler checks to see which type of enumeration it matches with and then takes the associated value that that instance contains.