June 17, 2014

Swift Arrays and Dictionaries with Various Types of Values using AnyObject

Posted in iPhone development, mac development tagged , , , , , at 7:25 pm by tetontech

Apple’s Swift documentation declares that Arrays and Dictionaries can only hold one type of value per collection. This is true but Apple’s examples are a little misleading. The code

var stArr:Array<String> = [“bob”,“sue”]

does create an Array named stArr that holds only strings. If you tried to add a number to stArr the code would fail to compile. The code

var anotherStrArr = [“sally”,“joe”]

would also create an Array that can only hold strings. An Array that can only hold Ints would be created from the code

var intArr = [4,56,7,12]

Whether the type is declared, as in the first example, or is the result of interpolation, as in the second and third example, only one type is storable in each of these Arrays.

What is not explained in Apple’s documentation is the use of AnyObject. The code

var interestingArray:Array<AnyObject> = [“sally”, “jones”, 45]

is not only legal, but it compiles and runs. Why?

Because all of the values in the array of of type AnyObject. An Array of AnyObjects can also be created by the interpolator.

var interpolatedInterestingArray = [“sally”“jones”, 45]

interestingArray and interpolatedInterestingArray will be identical in type and values. Understanding this isn’t particularly helpful if we restrict ourselves to Arrays. It can be very helpful when Dictionaries are being used. The code

var aPersonDictionary:<String,AnyObject> = [“firstName”:“sally”, “lastName”:“jones”, “age”:45]

is completely legal, creates a Swift Dictionary, and works well because all key-value pairs are of the same type: <String,AnyObject>. WARNING! The code

var interpolatedPersonDictionary = [“firstName”:“sally”“lastName”:“jones”“age”:45]

doesn’t yield the same result. Instead, the interpolator will assign a NSDictionary to the variable interpolatedPersonDictionary rather than a Swift Dictionary. This is important to know if you have a function that expects a Swift Dictionary. You can not directly pass an NSDictionary as a Swift Dictionary. They are not the same type.

My next post contains an operator and functions that need a Swift Dictionary using AnyObject rather than an interpolated NSDictionary.

Advertisements

2 Comments »

  1. Goutham said,

    how to pass dictionary one view to another view?

    • tetontech said,

      I’m not sure what you mean by this. Could you give more context to the question?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: