Programming in Swift · Dictionaries | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5994-programming-in-swift/lessons/31

Why would a dictionary give you nil and an array give you a fatal error for doing basically the same thing? Aren’t you asking for something “out of bounds” either way?

2 Likes

That’s an excellent question!

…and it has been the source of much debate over at https://forums.swift.org. There’s no easy answer!

Is there a preferred method to creating an empty dictionary? I’m not sure which to use (and why) between the following:

var namesAndAges: [String : Int] = [:]

var anotherEmptyDictionary = String : String

Is one preferred over the other; are there any additional ways of creating empty dictionaries?

Looks like some of my code was removed. Here’s a snippet:

40%20PM

Dictionaries return optional values, arrays return non-optional values (usually). So the syntax of using them is typically different. If an array could return nil, we would have to constantly unwrap the values in it.

I think they are interchangeable, and compile to the same thing.

1 Like