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 trialEndi Hıdır
1,762 PointsMy question about Casting Types in Swift
class Animal {}
class Dog: Animal {}
let a: Animal = Dog()
a as! Dog
This is Downcasting but Why can't we use normal casting like this: Dog(a) or Dog(a)!
I know "as" is using for converting from a class to one of its subclasses. But I can't understand why second method doesn't work ? Can someone explain the reason please.
1 Answer
Micah Howard
23,770 PointsHi Endi,
I am not sure where you are in the iOS coursework available on Treehouse, but I will attempt to answer your question. In your example, Dog is a subclass of Animal. This means that all of the properties and methods in the Animal class are inherited by the Dog class. So, you just have to assign the "Dog" class to the constant "a". "a" will be both a "Dog" and an "Animal". I hope this helps!
class Animal {}
class Dog: Animal {}
let a = Dog()