Basic Types
Swift's fundamental types — Int, Double, String, and Bool — and how the compiler enforces them.
អាន 2 នាទី
Swift's basic types cover the same ground you'd expect from any language — numbers, text, and true/false — but Swift is stricter about them than most, and that strictness is a feature, not friction.
Numbers: Int and Double
let age: Int = 30
let price: Double = 19.99Int holds whole numbers; Double holds decimals (specifically, a 64-bit floating-point number — precise enough for virtually everything you'll write). Swift also has Float for lower-precision decimals, but Double is the default you'll reach for almost always.
The strictness shows up the moment you mix them:
let quantity = 3 // Int
let unitPrice = 2.5 // Double
// let total = quantity * unitPrice // error: Int and Double can't multiply directly
let total = Double(quantity) * unitPrice // 7.5 — explicit conversion requiredMany languages silently convert Int to Double for you. Swift refuses, on purpose — an automatic conversion can lose precision or hide a mistake, so Swift makes you write Double(quantity) and be certain that's what you meant.
Strings
let greeting: String = "Hello"
let multiline = """
This string
spans multiple lines.
"""Strings in Swift are full Unicode-aware value types (more on what "value type" means in the structs-vs-classes lesson later). The triple-quote syntax above creates a multi-line string literal, useful for anything longer than a single line without escaping newlines manually.
Bool
let isComplete: Bool = false
let hasAccess = age >= 18 // inferred as BoolBool is only ever true or false — Swift has no concept of "truthy" values like 0 or an empty string standing in for false. This eliminates an entire class of bugs common in more permissive languages:
let count = 0
// if count { ... } // won't compile — Int isn't a Bool
if count == 0 { ... } // explicit comparison requiredType safety pays off later
It's tempting to see all this explicitness as extra typing for no benefit, but it compounds: every place a type mismatch would have been a runtime crash or a silently wrong calculation in a looser language, Swift turns it into a compiler error you fix before the code ever runs. As programs grow past a few hundred lines, that trade becomes one of the biggest reasons Swift codebases tend to have fewer surprises in production.
The next lesson covers string interpolation — the idiomatic way to build strings out of these basic types.