Every Swift program starts here, and the let-first style is how Swift code stays predictable.
Swift declares constants with let and variables with var. A let can be assigned once; the compiler rejects later changes. Idiomatic Swift uses let by default and switches to var only when a value really changes — Xcode even warns about a var that is never mutated.
Swift is statically typed but uses type inference: let count = 3 is an Int, let price = 9.99 is a Double. You can annotate explicitly with let ratio: Float = 0.5. The core types are Int, Double, Float, Bool, String and Character.
There are no implicit conversions between numeric types. Int plus Double is a compile error; convert explicitly with Double(count) or Int(price) (which truncates toward zero). This avoids silent precision loss.
Integer arithmetic traps on overflow instead of wrapping: Int.max + 1 crashes at run time. Use the overflow operators &+, &-, &* when you really want wrap-around.
printwrites to standard output, separating arguments with spaces.- Semicolons are only needed to put several statements on one line.
- Top-level code in
main.swiftor a script runs from top to bottom.
Names can be any Unicode identifier, but stick to lowerCamelCase for values and UpperCamelCase for types.
Example
let name = "Swift" // String, inferred
var version = 6 // Int
let pi: Double = 3.14159
version += 1
let total = Double(version) * pi // convert explicitly
print(name, version) // Swift 7
print(Int(total)) // 21 (truncates)
let big = Int8.max
print(big &+ 1) // -128 (wrapping operator)
// print(big + 1) // would trap: arithmetic overflowRemember
- Prefer
let; usevaronly for values that change - No implicit numeric conversions — convert with
Double(x),Int(y) - Overflow traps;
&+and friends wrap on purpose
Watch out for
- Expecting
Int(2.9)to round — it truncates to 2; use.rounded()first.