0
0
Swiftprogramming~5 mins

Explicit type annotation in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is explicit type annotation in Swift?
Explicit type annotation means telling Swift exactly what type a variable or constant should be, by writing the type after the name with a colon. For example, <code>let age: Int = 30</code> means <strong>age</strong> is an integer.
Click to reveal answer
beginner
Why use explicit type annotation in Swift?
You use explicit type annotation to make your code clearer, help the compiler catch mistakes early, and sometimes to fix ambiguous types when Swift can't guess the type on its own.
Click to reveal answer
beginner
How do you write explicit type annotation for a variable named name that holds a string?
You write: var name: String. This tells Swift that name will always hold text data.
Click to reveal answer
intermediate
What happens if you assign a value of the wrong type to a variable with explicit type annotation?
Swift will give a compile-time error because the value does not match the declared type. For example, if var age: Int and you try age = "thirty", it will not work.
Click to reveal answer
beginner
Can you give an example of explicit type annotation with a constant?
Yes! For example: <code>let pi: Double = 3.14159</code> means <strong>pi</strong> is a constant of type Double (decimal number).
Click to reveal answer
What does this Swift code do? var score: Int = 100
ADeclares a variable named score that holds a string value
BDeclares a constant named score with value 100
CDeclares a variable named score that holds an integer value 100
DDeclares a variable named score without a type
Why might you use explicit type annotation in Swift?
ATo allow variables to change type later
BTo make the program run faster
CTo avoid writing variable names
DTo make the code clearer and avoid type guessing errors
What error will Swift give if you write var count: Int = "five"?
ARuntime error when the program runs
BType mismatch error because "five" is a string, not an Int
CSyntax error because of missing semicolon
DNo error, Swift converts string to Int automatically
Which of these is a correct explicit type annotation for a Boolean variable named isOpen?
Avar isOpen: Bool = true
Bvar isOpen: Boolean = true
Cvar isOpen = true
Dvar isOpen: int = true
What does the colon (:) mean in let name: String?
AIt separates the variable name from its type
BIt assigns a value to the variable
CIt declares a function
DIt comments the code
Explain what explicit type annotation is and why it is useful in Swift.
Think about how you tell Swift exactly what kind of data a variable holds.
You got /4 concepts.
    Write an example of a Swift variable with explicit type annotation and explain each part.
    Try something like <code>var age: Int = 25</code> and explain it.
    You got /6 concepts.