Variables & Constants in Swift
Swift provides two ways to store values: variables (var) and constants (let).
Variables (var)
var score = 10
score = 20 // Valid
var name: String = "Alice" // Explicit type
Constants (let)
let pi = 3.14159
// pi = 3.14 // Error: Cannot assign to let
Type Inference
let message = "Hello" // Inferred as String
let count = 42 // Inferred as Int
let average = 3.14 // Inferred as Double
Optionals
var optionalName: String? = "Alice"
optionalName = nil
// Unwrapping
if let name = optionalName {
print("Hello, \(name)")
}
Type Aliases
typealias AudioSample = UInt16
var maxAmplitude: AudioSample = 32767
Common Types
Type | Example |
---|---|
Int | 42 |
Double | 3.14159 |
String | "Hello" |
Bool | true, false |