Playing with SpriteKit in a Swift Playground

UPDATE I have updated the playground and example for the latest version of XCode, you can view the new article here

swift playground spritekit

One of the great things about Playgrounds is that you can just start writing code. That's all well and good in a retro BASIC 10. PRINT "NIGEL IS ACE" way, but what about when you have a visual experiment to make. 

Playgrounds have a module called XCPlayground that makes this really easy. Any view can be mirrored into the time line (make sure you have the assistant view open, View->Assistant Editor). 

Here's a small snippet that gets a SpriteKit view open in Swift, and adds it to the time line (this is what they were doing in the Swift demo in the keynote). Just copy and paste it into a playground!

import SpriteKit
import XCPlayground

//Create the SpriteKit View
let view:SKView = SKView(frame: CGRectMake(0, 0, 1024, 768))

//Add it to the TimeLine
XCPShowView("Live View", view)

//Create the scene and add it to the view
let scene:SKScene = SKScene(size: CGSizeMake(1024, 768))
scene.scaleMode = SKSceneScaleMode.AspectFit

//Add something to it!
let redBox:SKSpriteNode = SKSpriteNode(color: SKColor.redColor(), size:CGSizeMake(300, 300))
redBox.position = CGPointMake(512, 384)
redBox.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(6, duration: 2)))