Which of the following Swift variable declarations correctly uses type inference?
easy📝 Conceptual Q2 of 15
Swift - Variables and Constants
Which of the following Swift variable declarations correctly uses type inference?
Alet greeting = "Hello, world!"
Bvar age: Int = "twenty"
Clet pi: Double = "3.14"
Dvar isActive = true as String
Step-by-Step Solution
Solution:
Step 1: Analyze each declaration
let greeting = "Hello, world!" assigns a String literal to a constant without explicit type, so type inference deduces String.
Step 2: Check for type mismatches
Options B and C assign String values to Int and Double types explicitly, which is invalid. var isActive = true as String tries to cast Bool to String incorrectly.
Final Answer:
let greeting = "Hello, world!" -> Option A
Quick Check:
Correct type inference matches assigned value type [OK]
Quick Trick:Match value type with inferred type [OK]
Common Mistakes:
Assigning String to Int or Double variables
Incorrect type casting
Confusing explicit type with inferred type
Master "Variables and Constants" in Swift
9 interactive learning modes - each teaches the same concept differently