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

Matthew Houston
Matthew Houston
7,203 Points

Casting in Programming and Using Swift

What is casting in programming. For example, what would casting look like using the Swift programming language?

Matthew, since you were asking in regards to Swift, I went ahead and updated the topic for you. I also edited the topic a bit. You usually can get more answers with a descriptive title. Hope you get some good answers on this.

3 Answers

Thiago de Bastos
Thiago de Bastos
14,556 Points

Hopefully these sources point you in the right direction!

"Casting is used when you, as the developer, have a reference to an object of type ClassA, but you >know that the object type is actually of type ClassB, where ClassB extends ClassA.

This comes into play for generic methods that return Object. You want to invoke methods of the >actual type, so you have to explicitly cast the Object to MyClass. Essentially, you are telling the >compiler you know what you are doing.

At runtime, if the Object is not a MyClass, you will get a RunTimeException.

A similar question has been answered over at stackexchange.


Casting and Type Conversions: C# Casting in Java

Answer to your second question ("What would casting look like in Swift?") here