Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build a Playlist Browser with Swift Building the Music Library and Playlist Models Struct Initialization

It's giving me an AnyObject? error and suggests i fix it with as!. Why do I need this in addition to String!?

Says "'AnyObject?' is not convertible to 'String!'; did you mean to use 'as!' to force downcast?" It gives me the fix option and works after i click on it.

4 Answers

Rafael Schwemmer
Rafael Schwemmer
6,108 Points

Here is the official explanation: https://developer.apple.com/swift/blog/?id=23

Basically, with Swift 1.2, Apple is separating the as operator into two different operators:

  • as for guaranteed conversion (e.g. upcasting from a class to its super class can never fail and is thus guaranteed)
  • as! for forced conversion (e.g. downcasting)

The forced conversion operator with the exclamation point indicates that conversion may fail in which case your app would crash at runtime.

Devin Scheu
Devin Scheu
66,191 Points

It's just needed to cast the objects. Some objects don't willingly convert to strings so casting can help out.

If you think my answer was good, feel free to mark it as best answer below, if you need more help in the future from me, you can contact me at devinwscheu@gmail.com.

Just curious why this force down casting with "as!" is different in the video? My version of Xcode is not many updates beyond what Pasan is using in this series.

Daniel Necula
Daniel Necula
1,645 Points

artists += playlistDictionary["artists"] as! [String]