Category: 01. Basic

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

  • Swift Nested Loops

    Swift Nested Loops

    Place a loop inside another loop to generate combinations or matrices.


    Generate combinations with nested loops

    Use inner and outer loops to produce pairs or grids from ranges and collections.

    Example

    for i in 1...2 {
      for j in 1...3 {
    
    print(i, j)
    } }


    Multiplication Table

    Use nested loops to build a small multiplication table.

    Example

    for i in 1...3 {
      var row = ""
      for j in 1...3 {
    
    row += "\(i*j) "
    } print(row) }

  • Swift For Loop

    Swift For Loop

    Use for-in to iterate over ranges, arrays, dictionaries, and other sequences.


    Iterate a Range

    Use a range to loop a fixed number of times.

    Example

    for i in 1...3 {
      print(i)
    }

    This example iterates from 1 to 3 inclusive.



    Iterate an Array

    Loop through an array with for-in or enumerated() to access index and value.

    Example

    let nums = [10, 20, 30]
    for n in nums {
      print(n)
    }
    for (index, value) in nums.enumerated() {
      print("index: \(index), value: \(value)")
    }

    Use enumerated() to get index and value together.

  • Swift While (Real-Life Examples)

    Swift While (Real-Life Examples)

    Use loops to retry operations, poll statuses, or process queues carefully with exit conditions.


    While Loop from 3 to 1

    Count down from 3 to 1.

    Example

    var remaining = 3
    while remaining > 0 {
      print("Remaining: \(remaining)")
      remaining -= 1
    }


    Poll Until Success

    Repeat an action with a cap on attempts until a condition is met.

    Example

    var attempts = 0
    var success = false
    while !success && attempts < 5 {
      attempts += 1
      print("Checking... #\(attempts)")
      if attempts == 3 {
    
    success = true
    print("Success!")
    } }
  • Swift Repeat/While Loop

    Swift Repeat/While Loop

    Use repeat { ... } while condition to run the body at least once.


    Repeat/while Loop Example

    This example uses a repeat/while loop to print “Try #1” and “Try #2”.

    Example

    var attempts = 0
    repeat {
      attempts += 1
      print("Attempt #\(attempts)")
    } while attempts < 3

    This example demonstrates repeat (do-while style).

    Tip: Avoid infinite loops. Ensure the loop condition will eventually become false.


    REMOVE ADS


    Runs Once Even If Condition Is False

    Because repeat checks the condition after the body, it executes at least once.

    Example

    var n = 0
    repeat {
      print("Runs once")
    } while n > 0
  • Swift While Loop

    Repeat code while a condition is true using while.

    Use repeat { ... } while to check the condition after the loop body.


    while

    The while loop checks the condition before each iteration.

    Example

    var n = 3
    while n > 0 {
      print(n)
      n -= 1
    }
    print("Liftoff!")

    This example counts down from 3 using a while loop.



    repeat { } while

    repeat runs the body first, then checks the condition.

    Example

    var attempts = 0
    repeat {
      attempts += 1
      print("Attempt #\(attempts)")
    } while attempts < 3

    This example demonstrates repeat (do-while style).

  • Swift Switch

    Swift Switch

    Use switch to match a value against patterns.

    In Swift, a switch must list every choice, and it stops checking more choices after the first match.


    Basic Switch

    Match integer ranges and exact values.

    Add default to handle remaining cases.

    Example

    let grade = 82
    switch grade {
    case 90...100:
      print("A")
    case 80..<90:
      print("B")
    case 70..<80:
      print("C")
    default:
      print("Below C")
    }

    This example categorizes a score using ranges in switch.

    Note: Swift switch must be exhaustive. Use default to cover remaining cases.



    String Switch

    Switch can match strings directly against literal cases.

    Example

    let command = "start"
    switch command {
    case "start":
      print("Starting")
    case "stop":
      print("Stopping")
    default:
      print("Unknown")
    }
  • Swift If (Real-Life Examples)

    Swift If (Real-Life Examples)

    Apply conditional logic to real situations like validation, feature flags, or permissions.


    Validate input with conditions

    Use conditions to validate input and guard against empty or invalid values.

    Example

    let input = "hello"
    if !input.isEmpty {
      print("Input received: \(input)")
    }

    When the input is empty, the code inside the condition is skipped.



    Feature Flag

    Gate a feature behind a flag and a user group.

    Example

    let enabled = true
    let userGroup = "beta"
    if enabled && userGroup == "beta" {
      print("Show feature")
    }

  • Swift If (Logical Operators)

    Swift If with Logical Operators

    Combine conditions with &&||, and negate with !.


    Combine conditions with logical operators

    Use AND, OR, and NOT to build complex conditions that control code paths.

    Example

    let isMember = true
    let hasCoupon = false
    if isMember || hasCoupon {
      print("Discount applied")
    }


    AND and NOT

    Combine conditions with && and negate with !.

    Example

    let isMember = true
    let expired = false
    if isMember && !expired {
      print("Active member")
    }

  • Swift Nested If

    Swift Nested If

    Nest if statements to check multiple levels of conditions.


    Use nested conditions for multi-step checks

    Use nested conditions to handle layered checks, such as authentication then role.

    Example

    let isLoggedIn = true
    let isAdmin = false
    if isLoggedIn {
    
    if isAdmin {
      print("Admin panel")
    } else {
      print("Limited access")
    }
    }

    Use nested conditions to handle layered checks, such as authentication then role.



    Validate and Branch

    Validate inputs first, then use a nested if to branch inside the valid case.

    Example

    let score = 85
    if score >= 0 && score <= 100 {
      if score >= 90 {
    
    print("A")
    } else if score >= 80 {
    print("B")
    } else if score >= 70 {
    print("C")
    } else {
    print("Below C")
    } } else { print("Invalid score") }
  • Swift Short Hand If…Else

    Swift Short Hand If…Else

    Use the ternary operator condition ? a : b for concise conditional expressions.


    Basic Ternary Operator

    Use the ternary operator to choose between two values in a single expression.

    Example

    let age = 20
    let status = (age >= 18) ? "Adult" : "Minor"
    print(status)

    This example returns “Adult” when age >= 18, otherwise “Minor”.


    REMOVE ADS


    Choose the Minimum

    Use a ternary expression to select the smaller of two values.

    Example

    let a = 5, b = 9
    let min = (a < b) ? a : b
    print(min)

    This prints the smaller number.

    If a is not less than b, the expression returns b.