Control transfer statements in SWIFT

Posted on 6/15/2014 @ 3:47 AM in #Swift by | Feedback | 1527 views

There are four control transfer statements in swift that deserve special mention,

  • continue
  • break
  • fallthrough
  • return
  • and .. labeled statements

 

break -

breaks the loop, and goes to the last }.

continue -

This is interesting! This restarts the loop. For instance, consider the below code,

   1:  var numbers = [1,2,3,4,5]
   2:  var oddNumbers = Int[]()
   3:  var evenNumbers = Int[]()
   4:   
   5:  for number in numbers {
   6:      if (number%2 == 1) {
   7:          oddNumbers.append(number)
   8:      } else {
   9:          continue
  10:          evenNumbers.append(number)
  11:      }
  12:  }
  13:   
  14:  oddNumbers
  15:  evenNumbers

This code will simply find all the Odd Numbers. What is interesting is, the even numbers array will be empty. This is because whenever the code encounters an even number, it will go back to the start of the loop and simply skip processing rest of the loop. Very handy!

fallthrough -

Switch statements in objective C do not require break. Soon as they process a condition i.e. match a case, they will exit the switch. If you wish to continue to evaluate rest of the cases after a match, include “fallthrough” at the end of your case.

return - 

Yeah this is what you think it is, returns values from functions.

labeled statements -

Sometimes you have multiple nested loops, and therefore it becomes useful to specify which loop we are breaking or continuing. This is achieved using labels. For instance, consider the code below,

   1:  var newMatrix:Dictionary<String, (Name:String, IsGoodPerson:Bool)[]> = [
   2:      "Humans":[("Neo", true),("Trinity", true), ("Cypher", false)],
   3:      "Programs":[("Agent Smith", false),("Agent Jones", false), ("Agent Sahil", false)]
   4:  ]
   5:   
   6:  var foundKey:String = ""
   7:  var firstBadPerson = String[]()
   8:   
   9:  allPeople:for key in newMatrix.keys {
  10:      foundKey = key
  11:      var persons = newMatrix[key]
  12:      for person in persons! {
  13:          var (personName, personType) = person
  14:          if personType == false {
  15:              firstBadPerson.append(personName)
  16:              continue allPeople
  17:          }
  18:      }
  19:  }
  20:  firstBadPerson


In this code, we are iterating over the characters of the movie matrix. And we intend to find the first bad person we encounter. As you can see, I am using a Dictionary, with a string as the key, and an array of a  tuple of (Name, IsGoodPerson)

The important thing to consider here is, soon as I run into a bad person in the dictionary element, there is no need to process rest of the array. So I say “continue”, but continue with the outer loop (not inside).

The output the above will produce is [“Agent Smith”, “Cypher”]

Purty neat!

Sound off but keep it civil:

Older comments..