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 trialjamiefang
10,798 PointsWhy don't we unwrap anything when we cast playlistDictionary["artists"] as [String]?
Why don't we unwrap anything when we cast playlistDictionary["artists"] as [String]?
Rasmus Rønholt
Courses Plus Student 17,358 PointsSure, arrays can be optionals... However, in this case he already initialised the property
var artists: [String] = [] //empty array (but instantiated and ready to use)
var artists: [String]? //optional of type array with strings
var artists: [String] //not optional, and will only compile if set in the designated initialiser
1 Answer
Rasmus Rønholt
Courses Plus Student 17,358 PointsThe value in playlistDictionary["artists"] is an array of strings. However the way the library is set up (just a big undefined array of data), the compiler has no way of knowing that. The speaker is merely telling the compiler that the value will be of type [String] ... again - he knows this because he hard coded the arrays - but the app would definitely crash if there was something else than an array of strings there... You could argue, however, that he doesn't need to unwrap anything in the preceding cases as well, so I get the confusion!
Robert Sheppard
2,549 PointsRobert Sheppard
2,549 PointsBecause [] denotes it as an array. It is first and foremost an array. I don't believe arrays can hold the anti-value nil. - I would appreciate if someone else could confirm that though.
If you look at the properties of the struct Playlist you will notice how everything that needed to be unwrapped(!) was defined as an optional(?), while the array which doesn't need to be unwrapped is clean and without the (?).
var largeIcon : UIImage? // this is an optional var artists: [String] = [] // this is an array