A place to breathe

Monday, July 7, 2014

Swift Syntax overview - more switch

Swift has powerful switch statement construct. Switch statement can compare multiple values, range, as well as tuples. The case statement can also do logic comparison. The following code demonstrates its capability

let myCar = "Ford Focus"
let yourCar = "Ford Fiesta"



switch car {

  case “BMW” :

      let myComment = “Need more cash”


   case let x where x.hasSuffix(“Ford”)   // put the content into   temp variable "x" and compare 


      let myComment = “your car now is \(x) ? “    // interpret the var x inside the bracket with slashes


  default:

     myComment = “Any car will do for me as long as it is cheap”

}
 


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





Swift Syntax overview - Array and Dictionary

We declare arrays in Swift as follows:

var myJobs = String()[]    //empty array
var myBooks = ["bus ride", "computer", "cars", "road to success"]    //initialize Array with values

Accessing it using array:

var bestSeller = myBooks[1]

Dictionary:

var bestBoss = Dictionary < String,Float > ()     //empty dictionary
var bestEmployee = [
       "Kyle" : "computer engineer",
       "Jason" : "web developer", 
       "Azeez" : "designer",


Sunday, July 6, 2014

Swift syntax overview - Part 1

I've reviewed a bit of Swift syntax, here's a highlight to save your time:

1. Type inference
Swift switch type declaration to facilitate "type-inference".

Int swiftVar ;   // old c-style
var swiftVar : Int    = 1    // type "Int" is now declared at the front 

var swiftVar   = 1           // type of swiftVar has been inferred as "Int"

It also means that Swift is a type-safe language i.e it needs to be specifically typed. Not like scripting language like JavaScript where you can just define any variable and not care about the type.

2. Typealias
Just like typedef, we can define it as

typealias myType = Uint16 
var yourType = myType.min

3. Constant v Variables
Constant is declared as "let" (C++  is "const").

let x = "Hello"  

x = "World"    //compile error ! changing const value


3. Integer conversion
Swift has a few built-in integer classes that is important for us to know:

Uint8, Uint16, Uint32, Uint64

If you define Uint, it'll be defined based on the platform (Uint32 on 32-bit platform, Uint64 on  64-bit platform).

Conversion between these  integer type variables must be done explicitly (Yawn).

let myInt : Uint8  = 1 
let myBigInt: Uint16 = 2000 

let newInt = myBigInt + Uint16(myInt) 

4. Tuple

I like this Tuple stuff. I am longing to have this in C-style language  (despite the fact that it is so easy to have tuples in scripting language)  .

let myBook = ( 1181818 , "Riding Bus for Dummies")  // declare the tuple 
let (code, title ) = myBook     // extract the tuples and place it nicely into the variable "code" and "title"
println ("The book code is \(code) and the title is \(title) ")

This reminds me of php "explode" function

5. Optionals

I was thinking hard about Swift syntax called "optionals", and I realized that this is probably coming from C-style conditional check:

(testValue) ? "this value " : "another value" ;

If I write this logic based on Swift's "Optional" , it is more like this:

(testValue) ?  "this value" : nil

But in swift, it is more than you think.

Int?   //  yes, this is what we call optional.it means, this value is either of type Int, or nil
var myInt:Int? = 2 
println(myInt!)
Int!  // implicitly unwrapped the optional when you try accessing it
var myInt:Int! = 2
println(myInt)  // no exclamation  mark.  I wonder why they do this.  


Enough for now.













Thursday, July 3, 2014

Swift and Objective-C ... and Cocos2D-Swift and Cocos2D.X

For a year since Nusantara Software released Tumeriq SDK on github,  we didn't really actively work on it anymore. Mostly because we're a bit confused on the direction of the language and platform in the mobile world. But it's time to reflect since we'll be going full force this year with our gaming platform.
As a developer of iOS back in 2011, we made decision to go all in with Apple platform. We bought Macs, iPhone, iPad, learn Objective-C, we made significant investments. We released a few games and we are really excited. And then Android came in with its own set of toolchains. I gave a few tries on Android tools and I didn't like it. So I just ignore Android.

Come to a point where Android users are now so significant,  that many requested our games to be ported to Android. The problem is, with customization of all the screen sizes that come with various forms, it was almost impossible for us to cater with very limited resources. Fortunately, Apportable is there so we can port the work onto Android.

I know there are many who are having this dilemma. Should I go all in with Cocos2D swift? Or should I go with cross platform Cocos2D.X? There's a danger of not using Swift, and there's a danger of not creating your game cross platform.

If we don't take the Swift path, we'll probably loose the power of the language itself. The demo shows that we can do rapid prototyping with Swift.  But the danger of getting into Swift is that, we'll probably get stuck with SpriteKit somehow, which I don't want.

Cocos2D.X is here to stay,  cocos2d-swift depends on Apple's direction. Should we go with Cocos2D.X or should we go full force with swift? To make matters worse, Swift is closed source (unlike Objective-C) and integrates heavily with XCode. To appreciate using Swift, we should also use XCode.

We'll probably have to make a tradeoff between Cocos2D.X and Swift for next Tumeriq release.
In the meantime, I'll learn Swift and enjoy the videos.


About Me

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