You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Swift has a rich type system that balances safety with expressiveness. This lesson covers how to declare variables and constants, the built-in types, type inference, and type conversions.
In Swift, you declare constants with let and variables with var:
let maximumAttempts = 10 // constant — cannot be changed
var currentAttempt = 1 // variable — can be reassigned
currentAttempt = 2 // OK
// maximumAttempts = 20 // Error: cannot assign to a 'let' constant
Best Practice: Prefer
letovervarwhenever possible. The compiler will warn you if you usevarfor a value that is never mutated.
Swift uses type inference, but you can add explicit type annotations:
let name: String = "Alice"
let age: Int = 30
let pi: Double = 3.14159
let isActive: Bool = true
When the type can be inferred from the value, you can omit the annotation:
let name = "Alice" // inferred as String
let age = 30 // inferred as Int
let pi = 3.14159 // inferred as Double
let isActive = true // inferred as Bool
| Type | Size | Range |
|---|---|---|
Int8 | 8-bit | -128 to 127 |
Int16 | 16-bit | -32,768 to 32,767 |
Int32 | 32-bit | -2.1 billion to 2.1 billion |
Int64 | 64-bit | Very large range |
Int | Platform-native | 64-bit on modern platforms |
UInt | Unsigned platform-native | 0 to very large |
Best Practice: Use
Intfor most integer values, even when the values are known to be non-negative. This promotes code consistency and interoperability.
| Type | Size | Precision |
|---|---|---|
Float | 32-bit | ~6 decimal digits |
Double | 64-bit | ~15 decimal digits |
Default: Swift infers
Doublefor floating-point literals.
let decimal = 17
let binary = 0b10001 // binary notation
let octal = 0o21 // octal notation
let hexadecimal = 0x11 // hexadecimal notation
// Underscores for readability
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_001
let greeting = "Hello, World!"
let empty = ""
let alsoEmpty = String()
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.