Category: 01. Basic

https://cdn3d.iconscout.com/3d/premium/thumb/book-3d-icon-png-download-8786672.png

  • Swift else if

    Swift else if

    Chain multiple conditions with else if for more than two branches.


    Branch with else if conditions

    Use else if for additional conditions when the first if is false.

    Example

    let score = 72
    if score >= 90 {
      print("A")
    } else if score >= 80 {
      print("B")
    } else if score >= 70 {
      print("C")
    } else {
      print("Below C")
    }

    This example evaluates multiple ranges using chained else if clauses.


    REMOVE ADS


    Temperature Levels

    Use multiple else if branches to categorize values.

    Example

    let t = 0
    if t <= 0 {
      print("Freezing")
    } else if t < 10 {
      print("Cold")
    } else if t < 20 {
      print("Cool")
    } else {
      print("Warm")
    }
  • Swift else

    Swift else

    Use else to handle the false branch of a condition.


    Handle the false branch with else

    Use else to run an alternate block when the condition is false.

    Example

    let hasAccess = false
    if hasAccess {
      print("Welcome")
    } else {
      print("Denied")
    }


    Age Gate

    Use else to handle when a user does not meet a requirement.

    Example

    let age = 16
    if age >= 18 {
      print("Access granted")
    } else {
      print("Access denied")
    }
  • Swift if

    Swift if

    Execute code conditionally when an expression evaluates to true.


    Basic if

    Run code only when a condition evaluates to true.

    Example

    let temp = 25
    if temp > 20 {
      print("Warm")
    }


    Threshold Check

    Trigger an action only when a value exceeds a threshold.

    Example

    let speed = 55
    if speed > 50 {
      print("Slow down")
    }
  • Swift If…Else

    Swift If…Else

    Control the flow of your program with ifelse if, and else.

    Combine conditions with logical operators.


    Basic If…Else

    Use if to run code when a condition is true.

    Add else for the false case, and else if for multiple branches.

    Example

    let score = 82
    if score >= 90 {
      print("A")
    } else if score >= 80 {
      print("B")
    } else {
      print("C or lower")
    }

    This example prints a letter grade based on the score.

    Tip: Swift conditions must be Bool.

    There is no implicit conversion from integers to booleans.



    Even or Odd

    Use else to handle the alternate outcome.

    Example

    let n = 7
    if n % 2 == 0 {
      print("Even")
    } else {
      print("Odd")
    }
  • Swift Ranges

    Swift Ranges

    Use ranges to express a sequence of values.

    a...b is a closed range including both ends.

    a..<b is a half-open range up to but not including b.


    Closed and Half-Open

    Use a...b for closed ranges (inclusive) and a..<b for half-open ranges (exclusive upper bound).

    Example

    for n in 1...5 {
    
      print(n)
    } 
    for n in 1..&lt;5 {
      print(n)
    }
    let r = 10...12
    print(r.contains(11))
    print(r.contains(13))

    This example iterates over closed and half-open ranges and checks membership with contains().



    One-Sided Ranges

    One sided ranges omit one end: ...b starts from the beginning, and a... goes to the end.

    Example

    let arr = [0, 1, 2, 3, 4]
    print(arr[...2])  // first three elements (indices 0...2)
    print(arr[2...])  // from index 2 to the end
  • Real-Life Examples

    Swift Arrays: Real-Life Examples

    Arrays are everywhere: rendering lists, aggregating values, finding items, and transforming data.


    Aggregate and Transform

    Use filtermap, and reduce to process arrays declaratively.

    Example

    let scores = [72, 88, 95, 64, 83]
    let passed = scores.filter { $0 >= 75 }
    let curved = passed.map { $0 + 5 }
    let average = curved.reduce(0, +) / curved.count
    print(passed)
    print(curved)
    print("Average: \(average)")

    Filter to keep passing scores, map to apply a curve, then reduce to compute an average.

    Tip: Prefer declarative iteration for clarity and fewer bugs.



    Search & Index

    Check for membership and find the index of a value.

    Example

    let names = ["Kai", "Bjorn", "Stale"]
    print(names.contains("Bjorn"))            // true
    if let i = names.firstIndex(of: "Stale") {
      print(i)                                 // 2
    }
  • Multidimensional

    Swift Arrays: Multidimensional

    Use nested arrays to represent 2D (or higher) structures such as matrices and grids.


    2D Arrays

    Store rows as arrays inside an outer array, then index as grid[row][col] to access items.

    Example

    var grid = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ]
    print(grid[0][1]) // 2
    for row in grid {
      print(row)
    }


    Update a Cell

    Change a value by indexing into the specific row and column.

    Example

    var grid = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ]
    grid[1][1] = 99
    print(grid[1])      // [4, 99, 6]
    print(grid[1][1])   // 99
  • Indices & Bounds

    Swift Arrays: Indices & Bounds

    Arrays have startIndex and endIndex (one past last).

    Use indices to loop valid positions.

    Out-of-bounds access crashes at runtime.


    Valid Indices

    Use indices to visit only valid positions.

    Example

    let items = [10, 20, 30]
    print(items.startIndex)       // 0
    for i in items.indices {
      print("index: \(i), value: \(items[i])")
    }

    Valid subscript indices: 0..<items.count (zero up to, not including, count).

    Example

    let items = [10, 20, 30]
    print(items[0])   // OK
    // print(items[3]) // out of bounds

    Use indices for index-and-value access without enumerated().

    Note: endIndex is not a valid subscript. The last valid index is items.index(before: items.endIndex).



    Last Valid Index

    Get the last valid index with index(before: endIndex).

    Example

    let items = [10, 20, 30]
    let lastIndex = items.index(before: items.endIndex)
    print(lastIndex)        // 2
    print(items[lastIndex]) // 30
  • Slices

    Swift Arrays: Slices

    Use ranges to create slices of arrays.

    A range is a half-open interval, meaning it includes the lower bound but excludes the upper bound.

    A slice is a view of an array that shares storage with the base array, meaning it is a reference to a portion of the array.

    When you modify a slice, the base array is also modified.


    ArraySlice

    Create an ArraySlice with a range on an array.

    Convert to Array if you need its own storage.

    Example

    let nums = [10, 20, 30, 40, 50]
    let middle = nums[1...3]          // ArraySlice<Int>
    print(middle)                     // [20, 30, 40]
    let copy = Array(middle)          // Array<Int>
    print(copy)

    Use a half-open range to exclude the upper bound:

    Example

    let nums = [10, 20, 30, 40, 50]
    let slice = nums[1..<3]   // indices 1 and 2
    print(slice)               // [20, 30]

    Slices share storage with the base array until you copy.

    Tip: Slices keep original indices.

    Convert to Array for zero-based indices.



    One-Sided Slices

    Use one-sided ranges to slice from the start or to the end.

    Example

    let arr = [0, 1, 2, 3, 4]
    print(arr[...2])  // first three elements (0...2)
    print(arr[2...])  // from index 2 to the end
  • Loop

    Swift Arrays: Loop

    Use for-in to loop values.

    Use enumerated() for index and value.


    Loop Elements

    Loop values with for-in, or use enumerated() for index and value.

    Example

    let fruits = ["Apple", "Banana", "Cherry"]
    for fruit in fruits {
      print(fruit)
    }
    for (i, fruit) in fruits.enumerated() {
      print("\(i): \(fruit)")
    }

    Get index and value with enumerated().



    forEach

    Use forEach for a functional style loop. It reads values but cannot use break/continue.

    Example

    let fruits = ["Apple", "Banana", "Cherry"]
    fruits.forEach { print($0) }
    fruits.enumerated().forEach { print("\($0.offset): \($0.element)") }