← Back to Swift Course | Chapter 14: Standard Library & Best Practices | Lesson 7 of 7

Swift Best Practices

Best practices are the tried-and-true habits experienced Swift developers follow to write code that's clean, safe, and easy for others to read.

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

markup
// 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))")

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

markup
// 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)")

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

markup
// 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))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Defaulting to class and force-unwrapping everywhere out of habit, instead of preferring struct, let, and safe optional handling by default.
  2. Writing overly clever one-liners that sacrifice readability, when Swift's clarity-focused design favors explicit, self-documenting code.
  3. Ignoring compiler warnings (like suggesting let over var) instead of treating them as free code-quality guidance.
Chapter Summary
  • Prefer let over var, and structs over classes, unless mutability or reference semantics are specifically needed.
  • Avoid force-unwrapping (!) except where a nil value 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 guard for 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.