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 Playlist Browser with Swift Building the Music Library and Playlist Models Using a Playlist Instance

Why do we "cast" the types?

couldn't we just declare them as the types we want them to be in the beginning? i'm new to this and think i must be missing something. Thanks!

Raul Gomez
Raul Gomez
Courses Plus Student 11,713 Points

depends on the language, a language like java requires you to cast the type other languages like ruby and python do not

1 Answer

Joshua C
Joshua C
51,696 Points

It's usually not recommended to cast an object just get rid of compiler errors. In most cases, yes, you do declare the data types in the beginning; however, sometimes objects in iOS are of type "id" in Objective-C or "AnyObject" in Swift and you want to tell the compiler that the object you're passing is of a specific type. For example, here is a good example in the Apple documentation about down casting:

for item in library {
    if let movie = item as? Movie {
        println("Movie: '\(movie.name)', dir. \(movie.director)")
    } else if let song = item as? Song {
        println("Song: '\(song.name)', by \(song.artist)")
    }
}

In this case, "item" is of type "AnyObject" and you want to check if the item is of type Movie or of type Song, so you cast the "item" object.

Here are is the link to the Apple docs I'm talking about: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html