Control Flow For Swift


Swift provides a variety of control flow statements. These include while loops to perform a task multiple times; ifguard, and switch statements to execute different branches of code based on certain conditions; and statements such as break and continue to transfer the flow of execution to another point in your code.
Swift also provides a for-in loop that makes it easy to iterate over arrays, dictionaries, ranges, strings, and other sequences.
Swift’s switch statement is considerably more powerful than its counterpart in many C-like languages. Cases can match many different patterns, including interval matches, tuples, and casts to a specific type. Matched values in a switch case can be bound to temporary constants or variables for use within the case’s body, and complex matching conditions can be expressed with a where clause for each case.

For-In Loops : 

  1. let names = ["Anna", "Alex", "Brian", "Jack"]
  2. for name in names {
  3. print("Hello, \(name)!")
  4. }

  1. for index in 1...5 {
  2. print("\(index) times 5 is \(index * 5)")
  3. }
  4. // 1 times 5 is 5
  5. // 2 times 5 is 10
  6. // 3 times 5 is 15
  7. // 4 times 5 is 20
  8. // 5 times 5 is 25


While Loops : 

Swift provides two kinds of while loops:
1. while evaluates its condition at the start of each pass through the loop.
2. repeat-while evaluates its condition at the end of each pass through the loop.
  • 
    
    while condition {
    
    
  •     statements
  • }
    
    
    For Example : 
    
    
    1. var square = 0
    2. var diceRoll = 0
    3. while square < finalSquare {
    4. // roll the dice
    5. diceRoll += 1
    6. if diceRoll == 7 { diceRoll = 1 }
    7. // move by the rolled amount
    8. square += diceRoll
    9. if square < board.count {
    10. // if we're still on the board, move up or down for a snake or a ladder
    11. square += board[square]
    12. }
    13. }
    14. print("Game over!")

    Repeat-While : 


    • repeat {
      
      
    •     statements 
    • 
      
      } while condition 
    For example :
    1. repeat {
    2. // move up or down for a snake or ladder
    3. square += board[square]
    4. // roll the dice
    5. diceRoll += 1
    6. if diceRoll == 7 { diceRoll = 1 }
    7. // move by the rolled amount
    8. square += diceRoll
    9. } while square < finalSquare
    10. print("Game over!")

    Conditional Statements : 

    If : All know about this one. and  its simplest form, the if statement has a single if condition. It executes a set of statements only if that condition is true.


    1. temperatureInFahrenheit = 72
    2. if temperatureInFahrenheit <= 32 {
    3. print("It's very cold. Consider wearing a scarf.")
    4. } else if temperatureInFahrenheit >= 86 {
    5. print("It's really warm. Don't forget to wear sunscreen.")
    6. }
    Switch :  switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. A switchstatement provides an alternative to the if statement for responding to multiple potential states.
    • switch some value to consider {
      
      
    • case value 1:
      
      
    •     respond to value 1
    • 
      
      case value 2,
    • 
      
           value 3:
    • 
      
          respond to value 2 or 3
    • 
      
      default:
    • 
      
          otherwise, do something else
    • }
      
      
      
      
      For example : 
      1. let someCharacter: Character = "z"
      2. switch someCharacter {
      3. case "a":
      4. print("The first letter of the alphabet")
      5. case "z":
      6. print("The last letter of the alphabet")
      7. default:
      8. print("Some other character")
      9. }
      10. // Prints "The last letter of the alphabet"
      The switch statement’s first case matches the first letter of the English alphabet, a, and its second case matches the last letter, z. Because the switch must have a case for every possible character, not just every alphabetic character, this switch statement uses a default case to match all characters other than a and z. This provision ensures that the switch statement is exhaustive.

      No Implicit Fallthrough : 

      1. let anotherCharacter: Character = "a"
      2. switch anotherCharacter {
      3. case "a": // Invalid, the case has an empty body
      4. case "A":
      5. print("The letter A")
      6. default:
      7. print("Not the letter A")
      8. }
      9. // This will report a compile-time error. So on 'case "a" needs some statement or a 'break" key word.

      Interval Matching : New features for Switch in side Swift

      Values in switch cases can be checked for their inclusion in an interval. This example uses number intervals to provide a natural-language count for numbers of any size:

      1. let approximateCount = 62
      2. let countedThings = "moons orbiting Saturn"
      3. let naturalCount: String
      4. switch approximateCount {
      5. case 0:
      6. naturalCount = "no"
      7. case 1..<5:
      8. naturalCount = "a few"
      9. case 5..<12:
      10. naturalCount = "several"
      11. case 12..<100:
      12. naturalCount = "dozens of"
      13. case 100..<1000:
      14. naturalCount = "hundreds of"
      15. default:
      16. naturalCount = "many"
      17. }
      18. print("There are \(naturalCount) \(countedThings).")
      19. // Prints "There are dozens of moons orbiting Saturn."

      Tuples

       You can use tuples to test multiple values in the same switch statement. Each element of the tuple can be tested against a different value or interval of values. Alternatively, use the underscore character (_), also known as the wildcard pattern, to match any possible value.

      1. let somePoint = (1, 1)
      2. switch somePoint {
      3. case (0, 0):
      4. print("\(somePoint) is at the origin")
      5. case (_, 0):
      6. print("\(somePoint) is on the x-axis")
      7. case (0, _):
      8. print("\(somePoint) is on the y-axis")
      9. case (-2...2, -2...2):
      10. print("\(somePoint) is inside the box")
      11. default:
      12. print("\(somePoint) is outside of the box")
      13. }
      14. // Prints "(1, 1) is inside the box"

      Value Bindings

      switch case can name the value or values it matches to temporary constants or variables, for use in the body of the case. This behavior is known as value binding, because the values are bound to temporary constants or variables within the case’s body.
      The example below takes an (x, y) point, expressed as a tuple of type (Int, Int), and categorizes it on the graph that follows:

      1. let anotherPoint = (2, 0)
      2. switch anotherPoint {
      3. case (let x, 0):
      4. print("on the x-axis with an x value of \(x)")
      5. case (0, let y):
      6. print("on the y-axis with a y value of \(y)")
      7. case let (x, y):
      8. print("somewhere else at (\(x), \(y))")
      9. }
      10. // Prints "on the x-axis with an x value of 2"

      Where

      switch case can use a where clause to check for additional conditions.
      The example below categorizes an (x, y) point on the following graph:

      1. let yetAnotherPoint = (1, -1)
      2. switch yetAnotherPoint {
      3. case let (x, y) where x == y:
      4. print("(\(x), \(y)) is on the line x == y")
      5. case let (x, y) where x == -y:
      6. print("(\(x), \(y)) is on the line x == -y")
      7. case let (x, y):
      8. print("(\(x), \(y)) is just some arbitrary point")
      9. }
      10. // Prints "(1, -1) is on the line x == -y"

      Compound Cases

      Multiple switch cases that share the same body can be combined by writing several patterns after case, with a comma between each of the patterns. If any of the patterns match, then the case is considered to match. The patterns can be written over multiple lines if the list is long. For example:

      1. let someCharacter: Character = "e"
      2. switch someCharacter {
      3. case "a", "e", "i", "o", "u":
      4. print("\(someCharacter) is a vowel")
      5. case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
      6. "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
      7. print("\(someCharacter) is a consonant")
      8. default:
      9. print("\(someCharacter) is not a vowel or a consonant")
      10. }
      11. // Prints "e is a vowel"
      // Another example
      let stillAnotherPoint = (9, 0)
      1. switch stillAnotherPoint {
      2. case (let distance, 0), (0, let distance):
      3. print("On an axis, \(distance) from the origin")
      4. default:
      5. print("Not on an axis")
      6. }
      7. // Prints "On an axis, 9 from the origin"

      Control Transfer Statements

      Control transfer statements change the order in which your code is executed, by transferring control from one piece of code to another. Swift has five control transfer statements:
      • continue
      • break
      • fallthrough
      • return
      • throw

      ContinueThe continue statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop. It says “I am done with the current loop iteration” without leaving the loop altogether.


      Break : 

      The break statement ends execution of an entire control flow statement immediately. The break statement can be used inside a switch or loop statement when you want to terminate the execution of the switch or loop statement earlier than would otherwise be the case.

      Break in a Loop Statement

      When used inside a loop statement, break ends the loop’s execution immediately and transfers control to the code after the loop’s closing brace (}). No further code from the current iteration of the loop is executed, and no further iterations of the loop are started.

      Break in a Switch Statement

      When used inside a switch statement, break causes the switch statement to end its execution immediately and to transfer control to the code after the switch statement’s closing brace (}).

      Fallthrough

      In Swift, switch statements don’t fall through the bottom of each case and into the next one. That is, the entire switch statement completes its execution as soon as the first matching case is completed. By contrast, C requires you to insert an explicit break statement at the end of every switch case to prevent fallthrough. Avoiding default fallthrough means that Swift switch statements are much more concise and predictable than their counterparts in C, and thus they avoid executing multiple switch cases by mistake.

      1. let integerToDescribe = 5
      2. var description = "The number \(integerToDescribe) is"
      3. switch integerToDescribe {
      4. case 2, 3, 5, 7, 11, 13, 17, 19:
      5. description += " a prime number, and also"
      6. fallthrough
      7. default:
      8. description += " an integer."
      9. }
      10. print(description)
      11. // Prints "The number 5 is a prime number, and also an integer."

Comments

Popular posts from this blog

iOS Architecture

Performance Tips for IOS Application

setNeedsLayout vs layoutIfNeeded Explained