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 2.0 Loading Data From a Resource Type Casting

Drew Carver
Drew Carver
5,189 Points

How is it that NSObject is being downcast to a native type in Swift?

In the video, he says:

"NSObject is an Objective-C type that is the base class for every object in the language. Similarly, AnyObject represents any class in Swift. Because they both represent very high-level types, they can be downcast to a more concrete type to a subclass further down the tree."

This doesn't make sense because NSObject is not a base class in Swift. How can it be downcast to String? What am I missing?

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Drew,

Yep, you can totally downcast an NSObject to a Swift type. Hit up a playground and try it out yourself!

totallyValidCode.swift
import Foundation

let nsTesting: NSObject = "Thingie"

let swiftyVersion: String = nsTesting as! String

This is because of the interoperability of Swift and Objective-C. I recommend checking out the Objective-C for Swift Developers course here on Treehouse, and/or the WWDC video Swift and Objective-C Interoperability from 2015.

Happy coding :beers:

-Greg