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 Swift Basics (retired) Collections What is a Dictionary?

Why do arrays not return optional values?

in this video it is explained, that while trying to access a value from the dictionary with a specific key, it is not certain that this key is indeed part of the dictionary's keys.

in the video before, we learned how to access an item from an array at a specific index. the todo-index had some 5 to 7 items. when trying to access an item at index 100, though, the index also does not hold a value. therefore, at least for my understanding, the danger of trying to access a value, that doesn't exist is not less present for an array, than it is for a dictionary. Nonetheless dictionaries return optionals, arrays don't. why?

3 Answers

Arrays have a count property which you can use to determine whether or not you are going to access an index which does not hold a value. If yourAttemptedIndex < array.count, then you know accessing that index is safe. Dictionaries don't generally have a specified order, so you don't usually know ahead of time whether or not the key you use will be in the Dictionary.

When you aren't explicit with your type annotations, Swift makes the choice to infer non-optional values for your array. You can come close to Dictionary behavior in an Array by being explicit:

var arr:[Int?] = [1, nil, 3]
arr[2] // {{Some 3}}

It will still result in a runtime error if you access beyond the count of the Array, however.

Max Hirsh
Max Hirsh
16,773 Points

Uh, don't think there's a policy. I did the same thing myself earlier XD. If you cut and paste your answer into the aswers section, I'll upvote you!

Max Hirsh
Max Hirsh
16,773 Points

I think krilnon has the answer to this question.

Oops, I accidentally put my answer in the comment section.

Is the policy here to leave it there, or remove it then copy down into the answer section? I'm new.