Author: saqibkhan

  • Swift Collections

    Swift Collections

    Use arrays, dictionaries, and sets to store ordered lists, key-value pairs, and unique items.


    Arrays

    Arrays store ordered lists of values.

    Syntax: [Type] for type, append with .append, count with .count, access with array[index].

    Example

    var nums: [Int] = [1, 2, 3]
    nums.append(4)
    print(nums.count)    // 4
    print(nums[0])       // 1

    This example creates an [Int] array, appends a value, reads the count, and accesses the first element.


    Dictionaries

    Dictionaries store key-value pairs.

    Syntax: [Key: Value] for type, assign with dict[key] = value, read with dict[key] ?? default.

    Example

    var ages: [String: Int] = ["Kai": 30]
    ages["Elisabeth"] = 25
    print(ages["Kai"] ?? 0)

    This example defines a [String: Int] dictionary, inserts a key, and reads with nil-coalescing.



    Sets

    Sets store unique items.

    Syntax: Set<Element> or literal, test membership with .contains.

    Example

    var letters: Set<Character> = ["a", "b", "a"]
    print(letters.contains("a"))
  • Swift Break/Continue

    Swift Break/Continue

    Use break to exit a loop early, and continue to skip to the next iteration.


    break

    Stop the loop immediately when a condition is met.

    Example

    for i in 1...10 {
      if i == 4 { break }
      print(i)
    }

    This example stops printing when i reaches 4.



    continue

    Skip the rest of the current iteration but keep looping.

    Example

    for i in 1...5 {
      if i % 2 == 0 { continue }
      print(i) // only odd numbers
    }
  • Swift For Loop (Real-Life)

    Swift For Loop (Real-Life)

    Use loops to process arrays, paginate data, or aggregate results.


    Process arrays and aggregate results

    Loop over a collection and accumulate values to compute totals like sums or averages.

    Example

    let numbers = [1,2,3,4,5]
    var sum = 0
    for n in numbers { sum += n }
    print(sum)


    Filter Even Numbers

    Filter a collection to keep only the values you need.

    Example

    let numbers = [1,2,3,4,5]
    let evens = numbers.filter { $0 % 2 == 0 }
    print(evens)
  • Swift For-Each Loop

    Swift For-Each Loop

    Use forEach to iterate sequences with a closure.


    Iterate with forEach closures

    Pass a closure to forEach to process each element of a sequence.

    Example

    ["A","B","C"].forEach { print($0) }


    Enumerated forEach

    Use enumerated() with forEach to get index and value.

    Example

    let items = ["A","B","C"]
    items.enumerated().forEach { print("\($0.offset): \($0.element)") }
  • 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")
    }