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

Whitman Huntley
Whitman Huntley
6,811 Points

If it's already in an if statement, why would we want to optionally type cast employee as hourlyEmployee also?

Wouldn't it be more efficient/cleaner to either cast hourly employee within an if/guard let statement OR an if statement, followed by a forced as!? What is the benefit to doing this? Or, is this just to show how to use as??

2 Answers

David Lin
David Lin
35,864 Points

I think what Whitman is asking is that ...

Instead of ...

if employee is HourlyEmployee {
    if let hourlyEmployee as? HourlyEmployee {
        hourlyEmployee.payWages(for: 10.0)
    }
}

... why not just do:

if let hourlyEmployee as? HourlyEmployee {
    hourlyEmployee.payWages(for: 10.0)
}

Yes, the first conditional check in the first example using "is" is redundant here. I think the teacher did it only to demonstrate the use of "is."

The second example effectively does exactly the same thing as the first.

Anthony Attard
Anthony Attard
43,915 Points

Because the object is not yet of the sub class until using the as. The if only checks the subclass but does not convert it.