Swift
Beginner
1 min read
Constants, Variables, and Type Inference
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