Author: saqibkhan

  • 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.

  • 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
    }