1. Basic Data Types
1
2
3
4
| let age: Int = 25
let price: Double = 19.99
let isActive: Bool = true
let name: String = "Swift"
|
Collections
1
2
3
| let numbers = [1, 2, 3] // Array
let uniqueNumbers = Set([1, 2, 3]) // Set
let user = ["id": 1, "name": "John"] // Dictionary
|
2. Constants vs Variables
let → Constant (cannot change)var → Variable (can change)
1
2
3
| let maxLoginAttempts = 10
var currentLoginAttempt = 0
currentLoginAttempt += 1
|
3. Type Inference
Swift automatically detects types:
1
2
| let count = 42 // Int
let pi = 3.14159 // Double
|
Explicit type declaration:
1
2
| var message: String
message = "Hello"
|
4. Optionals (Handling Missing Values)
Optionals represent values that may or may not exist.
1
2
| var possibleNumber: Int? = 123
possibleNumber = nil
|
Optional Binding
1
2
3
| if let number = possibleNumber {
print(number)
}
|
Default Value with ??
1
2
| let name: String? = nil
let greeting = "Hello, " + (name ?? "Guest")
|
5. Tuples (Multiple Values)
1
2
| let httpError = (404, "Not Found")
print(httpError.0) // 404
|
Named tuple:
1
2
| let status = (code: 200, message: "OK")
print(status.code)
|
6. Type Safety & Conversion
Swift prevents mixing incompatible types:
1
2
3
| let number = 3
let decimal = 0.14
let result = Double(number) + decimal
|
Explicit conversion is required.
7. Assertions & Preconditions
Assertion (debug only):
1
2
| let age = -1
assert(age >= 0, "Age cannot be negative")
|
Precondition (checked in production):
1
| precondition(age >= 0, "Invalid age")
|
8. Error Handling
1
2
3
4
5
6
7
8
9
| func makeSandwich() throws {
// may throw error
}
do {
try makeSandwich()
} catch {
print("An error occurred")
}
|
Key Takeaways
- Use
let by default. - Swift is strongly typed and safe.
- Optionals prevent null-related crashes.
- Explicit type conversion avoids hidden bugs.
- Assertions help catch mistakes early.