Complex data types 2
Type annotation – lets us dictate what data type each variable and constant should be
- summary
- checkpoint
Type annotation
Sometimes we want to override the default or we want to instantiate without defining the values.
let surname = "Lasso" // infers string var score = 0 // infers integer
Explicit
let surname:String = "Lasso" var score:Int = 0 // override var score:Double = 0
Types
// Simple let playnerName: String = "Roy" let luckyNumber: Int = 13 let pi: Double = 3.141 var isAuthenticated: Bool = true // Complex // arrays of strings var albums: [String] = ["Red", "Blue"] // dictionaries var user = [String:String] == ["id": "@username"] // set var books: Set<String> = Set([ "The Bluest Eye", "Foundation", "Girl, Woman, Other" ])
When its unnecessary…
// Swift already knows this contains Strings var soda = [String] = ["a", "b", "c"]
But it is necessary when creating an empty array
// Creating an empty array of Strings // These all do the same thing var teams: [String] = [String]() // or var teams = [String] = [] // or var teams = [String]()
Enums
enum UIStyle { case light, dark, system } var style = UIStyle.light var style:UIStyle = UIStyle.light style = .dark
Tip
Prefer type inference to explicitly setting except in the case of creating a constant where we don’t have values yet.
Opting to not use annotations for the most part makes the code shorter and easier to read
// instantiating a constant with no value let username: String // complex logic username = "@username" // complex logic print(username)
Scored 6/6 Type annotations
Summary
- Arrays store many values in one place and read them with indices
- They have to contain the same types of data
- they have useful functions: contains, count, append
- Dictionaries store many values and they are read using keys we specify
- they have useful functions: contains, count
- Sets store many values in a highly optimized way, we do not choose their order
- Enums create our own types to specify a range of acceptable values
- Swift uses type inferences by default to figure out what we are storing
- Type annotation forces a specific type
- Arrays get used the most by default, then dictionaries, then sets
- You’ll know when you need each
Coding convention
This is definitely a way to overcomplicate the application if not using type inference. Use annotations only when necessary.