0
0
Swiftprogramming~5 mins

Type inference by the compiler in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is type inference in Swift?
Type inference is when the Swift compiler automatically figures out the type of a variable or constant based on the value you assign to it, so you don't have to write the type explicitly.
Click to reveal answer
beginner
How does Swift infer the type of <code>let number = 10</code>?
Swift sees the value 10 is an integer, so it infers the type of number as Int.
Click to reveal answer
beginner
Can you give an example where type inference helps make code simpler?
Instead of writing <code>let name: String = "Alice"</code>, you can write <code>let name = "Alice"</code>. Swift infers <code>name</code> is a <code>String</code>.
Click to reveal answer
intermediate
What happens if Swift cannot infer the type?
If Swift cannot figure out the type from the value, it will give an error and ask you to specify the type explicitly.
Click to reveal answer
intermediate
Does type inference affect performance at runtime?
No, type inference happens only at compile time. The compiled program runs with explicit types, so there is no performance cost.
Click to reveal answer
What type does Swift infer for let pi = 3.14?
ADouble
BInt
CString
DFloat
Which of these requires explicit type annotation in Swift?
Alet count = 5
Blet message = "Hello"
Clet emptyArray = []
Dlet isActive = true
What is the benefit of type inference?
AAutomatically fixes bugs
BSlows down the program
CRemoves the need for variables
DMakes code shorter and easier to read
If you write let value = 42, what type does Swift assign to value?
AString
BInt
CDouble
DBool
What happens if you try to assign a different type to a variable after type inference?
ASwift throws a compile-time error
BSwift allows it without error
CSwift changes the variable's type automatically
DSwift ignores the new value
Explain what type inference is and why it is useful in Swift programming.
Think about how Swift guesses the type from the value you assign.
You got /4 concepts.
    Describe a situation where you must specify the type explicitly even when using type inference.
    When there is no value to guess the type from.
    You got /4 concepts.