let / var / Type Inference
In Swift, you declare constants with let and variables with var. Swift supports type inference, which automatically determines the type from the assigned value.
Syntax
// Constant (immutable) let constantName = value let constantName: Type = value // Variable (mutable) var variableName = value var variableName: Type = value
Syntax overview
| Syntax | Description |
|---|---|
| let name = value | Declares a constant. The value cannot be changed after assignment. |
| var name = value | Declares a variable. The value can be changed later. |
| let name: Type = value | Declares a constant with an explicit type annotation. Use this when type inference is ambiguous or when you want to make the intent clear. |
| var name: Type | Declares a variable with an explicit type. The initial value can be assigned later. |
Sample code
// Declaring a constant (inferred as Int)
let maxScore = 100
// Declaring and updating a variable
var score = 0
score = 85
// Declarations with explicit type annotations
let name: String = "Taro"
var height: Double = 170.5
// Type inference examples
let isActive = true // Inferred as Bool
let pi = 3.14159 // Inferred as Double
let greeting = "Hello" // Inferred as String
print("Name: \(name), Score: \(score)")
Overview
Swift is a type-safe language — every variable and constant has a type. Attempting to reassign a value to a constant declared with let results in a compile error. Use let whenever a value does not need to change to prevent unintended modifications.
Type inference automatically determines the type from the right-hand side value, so explicit type annotations are usually unnecessary. However, you must provide a type annotation (: Type) when declaring a variable without an initial value, or when you want a different type than what would be inferred.
For type casting, see Type casting (as / as? / as! / is).
If you find any errors or copyright issues, please contact us.