Complex Data Types 1
- How to store ordered data in arrays
- How to store and find data in dictionaries
- How to use sets for fast data lookup
- How to create and use enums
I’m not going to write more than necessary here.
How to store ordered data in Arrays
Capped on both ends with square brackets. Ex:
var a = ["a", "b", "c"] let b = [1, 2, 3] var c = [1.2, 3.5, 6.8]
To get the value via index. Indexes start w 0.
print(a[0]) print(b[1]) print(c[2])
Add data like so: Ex:
a.append("d") // a = ["a", "b", "c", "d"]
Did you know:
You can not mix data types in arrays. Type safety rules apply to Arrays.
So the arrays can also be written like this
// this array must hold data of type Int // the parenthesis allows you to change the way // you initialize the array var a = Array<String>() var b = Array<Int>() var c = Array<Double>() // can also be written like this: var a = [String]() var b = [Int]() var c = [Double]()
Removing items from the array
var chars = ["a", "b", "c"] print(chars.count) chars.remove(at: 2) print(chars.count) chars.removeAll() print(chars.count)
Checking to see if an item is in an array
let bondMovies = ["Casino Royale", "Spectre", "No Time to Die"] print(bondMovies.contains("Frozen")) print(bondMovies.contains("Spectre"))
Sort an array
let cities = ["London", "Tokyo", "Rome", "Budapest"] print(cities.sorted()) // ["Budapest", "London", "Rome", "Tokyo"]
Did you know:
For integers, sorted() will sort the array numerically
Sort in reverse? It doesn’t look like it worked, example unclear
let presidents = ["Bush", "Obaam", "Trump", "Biden"] let reversedPresidents = presidents.reversed() print(reversedPresidents)
Scored 6/6 on Arrays
How store and find data in dictionaries
Dictionaries are safer than arrays because they use keys. So if the data can be ordered sequentially and/or the order is not important we should use an Array. If we need to identify data by a key, we should use the Dictionary. If the data look up returns nil (empty), then that is a key that doesn’t exist.
// dictionary let employee = [ "name": "Baylor Smift", "job": "Writer", "location": "Nashville" ]
Accessing items
// these will produce warnings print(employee["name"]) print(employee["job"]) print(employee["location"]) // so lets provide defaults to clear the warnings print(employee["name", default: "Unknown"]) print(employee["job", default: "Unknown"]) print(employee["location", default: "Unknown"]) // They are safer becuase they proovide defaults in case the key is missing
we can mix data in dictionaries
// hasGraduated Array::String::Boolean // hasGraduated = [String: Boolean]() let hasGraduated = [ "Eric": false, "Maeve": true, "Otis": false ] // olympics Array::Int::String olympics = [Int: String]() let olympics = [ 2012: "London", 2016: "Rio", 2021: "Tokyo" ] // To access: the key is an int, the default is a string print(olympics[2012, default: "Unknown"])
Instantiate an empty dictionary
var heights = [String: Int]() heights["tall"] = 62 heights["short"] = 42 print(heights) // a great way to link data is with dictionaries var archEnemies = [String, String]() archEnemies["Batman"] = "The Joker" archEnemies["Superman"] = "Lex Luthor" archEnemies["X-Men"] = "Magneto" print(archEnemies)
Did you know:
Dictionary type data allows the default key so that if a key is requested that doesn’t exist, we can provide a default value.
You don’t always need a default value but is easy to provide one.
Provide a default value
let unknownArchEnemy = archEnemies["Green Lantern", default: "?"]
Scored 6/6 Dictionaries
Scored 11/12 Dictionary default values
i got caught with the missing semicolon between the default attribute and its value, moving too fast!
How to use sets for fast data lookup
Create a set of actorNames
let people = Set([ "Denzel Washington", "Tom Cruise", "Nicolas Cage", "Samuel L Jackson" ]) print(people)
Creating a set instantiates an array, the Set removess duplicates and it doesn’t care what order the array used.
Inserting items into the set
var actors = Set<String>() actors.insert("Wesley Snipes") print(actors)
Dictionaries strength is when using contains ie.
// a billion items in this set for instance var largeSet = Set<String>() // super fast! largeSet.contains("some item")
Sets
Unordered with no duplicatesArrays
Ordered and can contain duplicatesSets are optimized for fast retrieval
Scored 9/12 on Sets
Paul is throwing in some variations in questioning to really nail the understanding piece. I appreciate this because I’m a pattern guy and can breeze through multiple choice questions without really reading and that is a HUGE problem of mine. ๐
As stated on day 0, there is no reason to rush. From here on out I’m switching note-taking strategies.
I was pausing vid, writing notes, executing code in the playground. But that is breaking the flow of learning things. Going to try watching vid from end to end, taking notes from copy if necessary, and running code if unclear.
How to create and use enums
Enums solve the problems associated with using String values. Sometimes the data is just bad. If the data is stored in an enum, it prevents issues with bad data. The benefit is that the data is stored in a highly optimized fashion so there is a performance boost there as well.
enum Weekday { case monday, tuesday, wednesday, thursday, friday } var day = Weekday.monday day = Weekday.tuesday print(day) day = Weekday.wednesday print(day)
Once the data is assigned to a variable or constant its type is fixed so we can do this shorthand and Swift will know how to deal with it:
var day = Weekday.monday day = .tuesday print(day) day = .wednesday print(day)
Scored 6/6 on Enumerations