loop in swift

There are three types of loops available in Swift: the for-in loop, the while loop, and the repeat-while loop.

  1. The for-in loop:

    • It iterates over a sequence such as an array or a range.

    Example:

    main.swift
    let names = ["Alice", "Bob", "Charlie"]
    for name in names {
        print("Hello, \(name)!")
    }
    
    91 chars
    5 lines

    Output:

    main.swift
    Hello, Alice!
    Hello, Bob!
    Hello, Charlie!
    
    42 chars
    4 lines
  2. The while loop:

    • It repeats a block of code until the condition is false.

    Example:

    main.swift
    var x = 5
    while x > 0 {
        print(x)
        x -= 1
    }
    
    50 chars
    6 lines

    Output:

    main.swift
    5
    4
    3
    2
    1
    
    10 chars
    6 lines
  3. The repeat-while loop:

    • It is similar to the while loop except that it checks the condition at the end of the loop instead of the beginning.

    Example:

    main.swift
    var y = 5
    repeat {
        print(y)
        y -= 1
    } while y > 0
    
    57 chars
    6 lines

    Output:

    main.swift
    5
    4
    3
    2
    1
    
    10 chars
    6 lines

gistlibby LogSnag