Day 2 - 100 Days of Swift

5 minute read

Complex Data Types

Day 2 is about complex data types. It covers the collection types: Arrays, Sets, and Dictionaries, as well as Tuples and Enums. Here is my summary:

Arrays are ordered collections that, in Swift, contain items of all the same type. In fact, all of the collections can only hold items of the same type. They are declared like this:

1
2
3
4
5
6
7
var salesmen = ["Jim", "Dwight", "Andy", "Phyllis"]

var managers = [String]()
managers.append("Michael")

var hrReps: [String] = []
hrReps.append("Toby")

You read items like this:

1
let newestSalesman = salesmen[2]

Or assign them like this:

1
2
managers[0] = "Charles"
managers[0] = "Michael"

But things crash if you try to access an index that doesn’t exist in the array:

1
2
3
4
5
assistantManager = managers[1]
// Crashes!

hrReps[1] = "Holly"
// Also crashes!

Sets are unordered collections of unique items. They are declared like this:

1
2
3
4
5
6
7
8
var warehouseWorkers = Set(["Roy", "Darryl", "Madge"])

var clients = Set<String>()
clients.insert("Lackawanna County")

var angelasCats: Set<String> = []
angelasCats.insert("Mr. Pringles")

You can’t access items in a set by index because they are unordered, but you can look up if an item is in a set very quickly:

1
2
3
4
5
// Can't do this:
let foreman = warehouseWorkers[0]

// But you can do this:
let angelaIsHappy = angelasCats.contains("Mr. Pringles")

Dictionaries are an unordered collection of items that are associated with a key. The keys are unique, but the items aren’t. They are declared like this:

1
2
3
4
5
6
7
8
9
10
var jobTitles = [
"Pam" : "Receptionist",
"Jim" : "Salesman",
"Creed" : "Quality Assurance",
"Dwight" : "Salesman"
]

var dundies = [String: Int]()

var birthdays: [String: String] = [:]

You read items like this:

1
let dwightsTitle = jobTitles["Dwight"]

If there isn’t a value, the dictionary will return nil, which means there isn’t anything there, but you can give it a default value like this:

1
2
3
4
5
let kevinsDundies = dundies["Kevin"]
// returns nil

let oscarsDundies = dundies["Oscar", default: 0]
// returns 0

You assign the value for a key like this:

1
2
3
4
5
jobTitles["Dwight"] = "Assistant to the Regional Manager"

// some time later...

jobTitles["Dwight"] = "Assistant Regional Manager"

Tuples are a way to bundle up a group of related values. They are ordered, that can have names, and they don’t have to be of the same type. They are declared like this:

1
2
3
let officeLocation = (latitude: 41.40121, longitude: -75.67336)

var officeAddress = (street: "1725 Slough Ave", city: "Scranton", state: "PA", zip: 18503)

The items don’t have to all be of the same type, but their types cannot change. So this won’t work:

1
officeAddress.zip = "18505"

But this will:

1
officeAddress.zip = 18505

You can access items either by index or by name, if it exists:

1
2
3
let officeLatitude = officeLocation.0

let officeLongitude = officeLocation.longitude

Enums are a way of grouping like values and are defined like this:

1
2
3
enum Workday {
	case monday, tuesday, wednesday, thursday, friday
}

And used like this:

1
2
3
let takingVactionOn = Workday.monday

let humpday: Workday = .wednesday

Each case can have associated values, to store related information:

1
2
3
4
5
enum Activity {
	case talking(with: Customer)
	case pullingPranks(on: Coworker)
	case flirting(with: Receptionist)
}

Or you can define a raw value for the cases:

1
2
3
4
5
enum StanleyStatus: String {
	case sleeping = "asleep"
	case disgruntled
	case furious
}

This allows you to dynamically create a case from a value, or access the value of the case:

1
2
3
4
5
6
var currentStatus = StanleyStatus(rawvalue: "disgruntled")

currentStatus = .sleeping

print("Stanley is currently \(currentStatus.rawValue)")
// -> "Stanley is currently asleep"

Reflections

So far we haven’t written much code that actually does anything. It has mostly been about defining terms and understanding the basic rules. Like yesterday, it was mostly syntax that I was familiar with going in, but it was good practice thinking about the kind of things that would best be encapsulated in each of the various types. Also, I didn’t know that the structure of a tuple can’t be changed once it is defined. When I first read that, I thought “that can’t be true” because I use tuples all the time and I’ve never gotten an error about it. But I realized that I just happen to never use tuples in a way that would need to change their structure, so I have never run into that constraint. It’s only day 2 and I’ve already learned something I don’t know. Didn’t take long.