A place to breathe

Monday, July 7, 2014

Swift Syntax overview - Control

Control Structure 

With the exception of the bracket (for whatever reason) when  we try to iterate in for loop or at the if-else statement, the control in Swift can be considered normal: 

let gameScorePerLevel =  [ 20, 25, 30 ]

var totalBonus = 0 

for score in gameScorePerLevel {
    if score > 30 { 
        totalBonus += 5 
    } else if score > 40 {
        totalBonus += 6 
     } 
 } 


Fallthrough in switch statements

By default, Swift doesn't have the "break" statement because at the end of the "case" statement, it will break. But because C-style programming is avoiding "break" to let the cases fallthrough, so the opposite is introduced in Swift with the 'fallthrough" statement:

let currentLevel = 2
let levelScore = 50 
var currentLife : Int = 1

var levelDescription = "Your score for \(currentLevel) is \(levelScore) " 

switch levelScore { 
      case 10,20 : 
         // update description and break out of the switch stmt
          levelDescription +=  "but you did not get any additional life"
      case 30,40,50 : 
         currentLife += 1    
         levelDescription +=  "and you get extra life"
         fallthrough     // fall to the default stmt
      default: 
         currentLife += 1    //extra bonus life
         levelDescription += "and another bonus life"
}




Labeled Statement


Cool things added to swift is you can label your control statement. For example, if you have a simple arcade shootout game that ask you to fire a target ball with limited attempt, you can just simply do the following loop, and

let attempt = 5 
var totalBall = 10

ballGameLoop : while totalBall > 0 { 

   if attempt == 0 { break ballGameLoop }  // we can go out of the label loop here. Game Over.
 
   switch  ballHit {  

       case targetBall : 
              break ballGameLoop     // we win so go out of labelled loop to finish the game
 
    default : 
           --attempt    
           -- totalBall
       }
         
}





No comments:

About Me

I'm currently a software engineer. My specific interest is games and networking. I'm running software company called Nusantara Software.