Type annotations <== This phrase is used a LOT in SwiftUI and Swift documentation and videos.
We mostly can guess the type of a variable when it's defined. Let's try!
let someVariable = 2 // What type are we storing here? Have a guess!
var anotherVariable = "Please press the Like button and subscribe!"
This isn't a problem. We can see the first is an Int
and the second is a String
.
But in some cases, you'll not have data ready to use. But you need to reserve the variable. In this case, you'll want to LEAVE A NOTE to let Swift know what you plan to use. You will annotate your declaration with the TYPES you plan to use.
let someVariable : Int // leaving a NOTE for Swift.
let anotherVariable : String // this is Type Annotation.
As @nigel points out above, when you want to declare a dictionary, you can let Swift guess by providing default values. But if you want to declare a dictionary without default data, you have to use TYPE ANNOTATION to let Swift know what types you'll be using in the dictionary.
// Declare a dictionary by type inference. (Let Swift guess the types!)
var osDictionary = ["Macintosh": "MacOS", "iPhone" : "iOS", "Watch" : "WatchOS" ] // Inferred types.
// Declare a dictionary by type annotation. (Leave a note for Swift ... )
var someDictionary: [String: String] // This is a note for Swift
var otherDictionary: [String: Double] // Swift doesn't have data yet, but knows what you'll be storing.