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 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,109 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]