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 Vending Machine App in Swift Loading Data From a Resource Type Casting

Lana Wong
Lana Wong
3,968 Points

What does hourlyEmployee Stand for?

In Line 43, it say: if let hourlyEmployee = employee as! HourlyEmployee.

What does hourlyEmployee stand for? Did we create a new constant, or just change the type of the instance "hourlyEmployee", created on Line 36?

1 Answer

Ian Billings
PLUS
Ian Billings
Courses Plus Student 7,494 Points

Hi Lana,

The hourlyEmployee in line 35 is added to an array with salariedEmployee on line 38. Because elements of an array have to be of the same type, the compiler upcasts the two instances to their parent class, which is Employee. Therefore, functionality that is available to HourlyEmployee class objects aren't available to the first element of the array even though the underlying type is of HourlyEmployee. Therefore, what Pasan is doing is down casting the element back down to an HourlyEmployee type. As down casting can fail (could return nil) Pasan uses an if let to check that the downcast is successful before attempting to use HourlyEmployee specific functionality. So in the end, the hourlyEmployee on line 43 is the same as the one earlier, and he can use the same variable name because the second variable is only useable within the for loop.

Hope that makes sense,

Ian