Casting an Int to a Float

To cast an Int to a Float:

let someInt: Int = 3
let someFloat: CGFloat = CGFloat(someInt)

This is useful if you’d like to generate a random float:

let randomY = CGFloat(arc4random() % 1000) / 1000
 

2048 implemented in Swift

There’s a new game clone of the 2048 game written in Swift: https://github.com/austinzheng/swift-2048. The author also provides some feedback on Swift:

  • Great language, feels like programming in Scala
  • misses closure based callbacks for UIKit – selectors seem like a hack in Swift
  • private, public, protected for class properties seem missing
  • initializing n-dimension arrays is painful
  • XCode still very unstable
 

Debug SKPhysicsBody with Swift

Here’s a small extensions that will help you debug SKPhysicsBody Objects using Swift:

extension SKNode {
    func attachDebugRectWithSize(s:CGSize) {
        let bodyPath = CGPathCreateWithRect(CGRectMake(-s.width/2, -s.height/2, s.width, s.height), nil)
        self.attachDebugFrameFromPath(bodyPath)
        CGPathRelease(bodyPath)
    }

    func attachDebugFrameFromPath(path:CGPathRef) {
        var shape = SKShapeNode()
        shape.path = path
        shape.strokeColor = SKColor(red: 1.0, green: 0, blue: 0, alpha: 0.5)
        shape.lineWidth = 2.0
        shape.zPosition = 200
        self.addChild(shape)
    }
}

You can use it like this:

//..
let groundRect = CGRectMake(0, groundTexture.size().height, self.frame.size.width*2, groundTexture.size().height)
var ground = SKNode()
ground.position = groundRect.origin
ground.physicsBody = SKPhysicsBody(rectangleOfSize: groundRect.size)
ground.physicsBody.dynamic = false
ground.attachDebugRectWithSize(groundRect.size)
 

Swift support for vim

There’s already a project on github to support Swift coding in vim: https://github.com/toyamarinyon/vim-swift

To install using NeoBundle, put this in your .vimrc:

NeoBundle 'toyamarinyon/vim-swift'

Then run :NeoBundleInstall

 

For loops

Iterate by incrementing or decrementing a value

for var i = 0; i < 10; i++ {
  // do something
}

// alternative:
for i in 0...10 {
  // do something
}

To iterate over an array in Swift:

for x in ["a", "b", "c"] {
  // do something
}

To iterate over a dictionary in Swift:

for (key, val) in ["foo": 23, "bar": 244, "baz": 42] {
  // do something
}
 

“FlappyBird” clone using Swift

The folks at fullstack.io created a “FlappyBird” clone using Swift. You can view the code on github. If you browse the code you’ll notice how readable and expressive Swift is – the whole codebase is just around 400 lines of code!