Subscribe now

Practice using Arrays and Dictionaries [11.09.2016]

Create an array with a String, Int and Bool in it.

Create an empty dictionary which maps Ints to Strings. Then insert "daily" for 1, and "drip" for 2.

Create a String with the contents of the above items.

Print these to the console.

Solution

Create an array with a String, Int and Bool in it.

The trick here is that Swift’s type inference has trouble with different types in an array, so you’ll need to specify it as an [Any] explicitly.

var anArray:[Any] = ["1", 1, true]

Create an empty dictionary which holds Strings for a given Int key.

var aDictionary:[Int:String] = [:]

Then insert "daily" for 1, and "drip" for 2.

aDictionary[1] = "daily"
aDictionary[2] = "drip"

Create a String with the contents of the above items.

var theString:String = "array = \(anArray), dictionary = \(aDictionary)"

Print these to the console.

print(theString)