SyntaxStudy
Sign Up
Swift Constants, Variables, and Type Inference
Swift Beginner 1 min read

Constants, Variables, and Type Inference

Swift uses let for constants and var for variables. Type inference lets the compiler deduce the type from the assigned value, keeping code concise while remaining fully type-safe. Explicit type annotations are written with a colon: var age: Int = 30. This is required when the type cannot be inferred or when you want to be explicit for clarity. Swift's type system is static — once a variable's type is set (either explicitly or by inference), it cannot change. This catches type errors at compile time.
Example
// Type inference
let city = "Tokyo"          // String
let population = 13_960_000 // Int (underscores for readability)
let density = 6_158.3       // Double
let isCapital = true        // Bool

// Explicit annotations
var temperature: Float = 36.6
var count: Int = 0

// Multiple assignment
var x = 0, y = 0, z = 0

// Type conversion (must be explicit)
let intVal: Int = 10
let doubleVal: Double = Double(intVal)
let strVal: String = String(intVal)

// Tuples
let coordinates = (latitude: 35.6762, longitude: 139.6503)
print(coordinates.latitude)

let (lat, lon) = coordinates
print("Lat: \(lat), Lon: \(lon)")

// Type aliases
typealias UserID = Int
typealias Score = Double

var userId: UserID = 42
var userScore: Score = 98.5