Swift Best Practices
Prefer let and Value Types
Defaulting to let and structs produces code that's easier to reason about, since values can't unexpectedly change from elsewhere in the program.
Example: Prefer let and Value Types
// Define a struct `Point`
struct Point {
let x: Int
let y: Int
}
// Declare a constant `origin`, set to `Point(x: 0, y: 0)`
let origin = Point(x: 0, y: 0)
// Print "Origin: (\(origin.x), \(origin.y))" to the console
print("Origin: (\(origin.x), \(origin.y))")
Login to try C/C++/Java/PHP code in the editor
Avoid Force Unwrapping
Using if let, guard let, or ?? instead of ! avoids crashes when a value turns out to be missing, making code more resilient.
Example: Avoid Force Unwrapping
// Define the function `safeDivide` taking `a`, `b` and returning a `Int?`
func safeDivide(_ a: Int, by b: Int) -> Int? {
guard b != 0 else { return nil }
// Return `a / b` from this function
return a / b
}
// Declare a constant `result`, set to `safeDivide(10, by: 0) ?? 0`
let result = safeDivide(10, by: 0) ?? 0
// Print "Safe result: \(result)" to the console
print("Safe result: \(result)")
Login to try C/C++/Java/PHP code in the editor
Write Self-Documenting Code
Descriptive names for functions, parameters, and variables make code readable without needing extra comments to explain what it does.
Example: Write Self-Documenting Code
// Define the function `calculateTotalPrice` taking `itemPrice`, `quantity`, `taxRate` and returning a Double
func calculateTotalPrice(itemPrice: Double, quantity: Int, taxRate: Double) -> Double {
// Declare a constant `subtotal`, set to `itemPrice * Double(quantity)`
let subtotal = itemPrice * Double(quantity)
// Return `subtotal + (subtotal * taxRate)` from this function
return subtotal + (subtotal * taxRate)
}
// Print `calculateTotalPrice(itemPrice: 20.0, quantity: 3, taxRate: 0.08)` to the console
print(calculateTotalPrice(itemPrice: 20.0, quantity: 3, taxRate: 0.08))
Login to try C/C++/Java/PHP code in the editor
- Defaulting to
classand force-unwrapping everywhere out of habit, instead of preferringstruct,let, and safe optional handling by default. - Writing overly clever one-liners that sacrifice readability, when Swift's clarity-focused design favors explicit, self-documenting code.
- Ignoring compiler warnings (like suggesting
letovervar) instead of treating them as free code-quality guidance.
- Prefer
letovervar, and structs over classes, unless mutability or reference semantics are specifically needed. - Avoid force-unwrapping (
!) except where anilvalue would represent a genuine programming error. - Use clear, descriptive names and let Swift's type inference reduce noise without sacrificing clarity.
- Lean on the compiler: address warnings, use
guardfor early exits, and let strong typing catch bugs early.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: