Types and Strings
Type Annotations
When the intended type should be explicit, write the type after a colon.
Declare the type you want
type_annotations.swift
Replay: real traced execution (multi-file project)
let width: Int = 8
let height: Int = 3
let title: String = "panel"
let area: Int = width * height
let summary: String = "\(title): \(area)"
print(summary)
let width: Int = 5
let height: Int = 3
let title: String = "panel"
let area: Int = width * height
let summary: String = "\(title): \(area)"
print(summary)
let width: Int = 12
let height: Int = 3
let title: String = "panel"
let area: Int = width * height
let summary: String = "\(title): \(area)"
print(summary)
width ← 8, height ← 3, title ← panel, area ← 24, summary ← panel: 24
1let width→ 8: Int = 8 //@width=5, 122let height→ 3: Int = 33let title→ panel: String = "panel"4let area→ 24: Int = width8 * height35let summary→ panel: 24: String = "\(titlepanel): \(area24)"67print(summarypanel: 24)outputpanel: 24
width ← 5, height ← 3, title ← panel, area ← 15, summary ← panel: 15
1let width→ 5: Int = 52let height→ 3: Int = 33let title→ panel: String = "panel"4let area→ 15: Int = width5 * height35let summary→ panel: 15: String = "\(titlepanel): \(area15)"67print(summarypanel: 15)outputpanel: 15
width ← 12, height ← 3, title ← panel, area ← 36, summary ← panel: 36
1let width→ 12: Int = 122let height→ 3: Int = 33let title→ panel: String = "panel"4let area→ 36: Int = width12 * height35let summary→ panel: 36: String = "\(titlepanel): \(area36)"67print(summarypanel: 36)outputpanel: 36
Follow the Area
widthstarts at8.heightis3.titleispanel.area = width * heightbecomes24.summarybecomespanel: 24, and the program prints it. | width | height | area | summary | | --- | --- | --- | --- | | 5 | 3 | 15 | panel: 15 | | 8 | 3 | 24 | panel: 24 | | 12 | 3 | 36 | panel: 36 |
annotation
`let name: Type = value` tells Swift the exact type expected for the value.
Exercise: type_annotations.swift
Reproduce panel: 24, then use width 5 and 12 to predict each summary.