June 17, 2014
Swift Arrays and Dictionaries with Various Types of Values using AnyObject
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.