Hello Swift/Playgrounds

Swift logoWow, it's been a while. I have to say, the combination of Swift and Playgrounds (in XCode 6) brings a lot of fun. I spent the night playing with it, and I wanted to share a piece of code you can try and get started quickly. I could talk about the details of the language and how nice it is, as an F# lover, I love that Swift got some inspiration from it (and other languages too).

With the combination of SpriteKit, similar to Starling, you guys should feel at home.

So there we go, I will post more articles in the next weeks (if you guys like the idea) about my Swift experiments and how the language works, but let's start with a classic Flash dev Hello World with some simple API calls, to make something move over time with an EnterFrame style event:

// Playground - noun: a place where people can play
// Consider this your Main class, basically the Stage
// Note: The code below is for OSX Playground, not iOS

// this imports higher level APIs like Starling
import SpriteKit
import XCPlayground

// our main logic inside this class
class GameScene: SKScene {
    
    // properties initialization
    // note that the spriteNode property below is not initialized
    // we initialize it through the init initializer below
    var spriteNode: SKSpriteNode
    var i = 0.0
    
    // this is our initializer, called once when the scene is created
    // we do our initialization/setup here
    init(size: CGSize){
        
        // let's grab an image, like [Embed] in AS3, results in image data like BitmapData
        // let is to declare a constant, var a variable
        // note that we don't type things, you actually can to resolve ambiguity sometimes
        // but it is inferred by default and does not cause performance issues to not statically type
        let sprite = NSImage(contentsOfFile:"/Users/timbert/Documents/Adium.png")
        
        // let's create a bitmap, like Bitmap in AS3
        let myTexture = SKTexture(image: sprite)
    
        // let's wrap it inside a node
        spriteNode = SKSpriteNode(texture: myTexture)
        
        // we position it, we could scale it, etc.
        spriteNode.position = CGPoint (x: 250, y: 250)
        
        // we complete the initialization by initializating the superclass
        super.init(size: size)
    }
    
    // this gets triggered automtically when the scene is presented by the view
    // similar to Event.ADDED_TO_STAGE
    override func didMoveToView(view: SKView) {
        
        // let's add it to the display list
        self.addChild(spriteNode)
    }
    
    // we override update, which is like an Event.ENTER_FRAME or advanceTime in Starling
    override func update(currentTime: CFTimeInterval) {
        i += 0.1
        // oscillation with sin, like Math.sin
        var osc = 1.5 + sin(CDouble(i))
        // let's scale it
        spriteNode.setScale(CGFloat(osc))
        // we could have retrieved spriteNode also with the code below, similar to getChildAt(0)
        //let node = self.children[0] as SKSpriteNode
    }
}

// we create our scene (from our GameScene above), like a main canvas
let scene = GameScene(size: CGSize(width: 500, height: 500))

// we need a view
let view = SKView(frame: NSRect(x: 0, y: 0, width: 500, height: 500))

// we link both
view.presentScene(scene)

// display it, XCPShowView is a global function that paints the final scene
XCPShowView("result", view)

This should give you the following animation (scaled bitmap) in Playgrounds:

Swift Playgrounds Hello World

Comments (23)

  1. Catmembert wrote:

    Wooooooooot ! This is so cool dude. And yes I am definitely interested in more articles about Swift :-)

    Wednesday, June 4, 2014 at 9:57 am #
  2. Bethip wrote:

    Very nice Thibault. Alas I haven’t got very far. Do you know why I get the above error? Everything else seems ok if I comment this import out. Very very new to this stuff! Cheers

    Wednesday, June 4, 2014 at 12:32 pm #
  3. Nice to see you playing with Swift! Bring back memories from the old Flash days.
    I’m really excited about Swift too, I’m almost finishing the programming guide and I gotta say it looks very promising!

    Wednesday, June 4, 2014 at 4:33 pm #
  4. Nick wrote:

    Hi, I get an error saying that XCPlayground is not present. Could you please help me with that?

    Thursday, June 5, 2014 at 5:29 am #
  5. Andrey wrote:

    Hey Thibault,
    It’s pretty sad that you haven’t posted anything for more than a year now, and you’re so excited about Swift, just right here, at one of the best Action Script blogs on the internet.

    It’s really awful how you, Adobe guys, sold your souls, left all of us doing AS and now push Apple forward by various ways.

    My advise would be to stop posting here, as it would turn this little Flash evangelistic heaven into bunch of crap. I know none of you will ever speak why Adobe dropped AS and Flash, but at least don’t try to advertise new thins to us, as most of the people out there still think of you as Thibault, the Flash guru..

    Thursday, June 5, 2014 at 10:19 am #
  6. I want to learn Swift but I don`t have a Mac will there be any support for it on Windows or Linux?

    Thursday, June 5, 2014 at 11:35 am #
  7. Thibault Imbert wrote:

    Hi Nick,

    Sure. What exact error do you get? (from the output window).

    Is is the call to XCPShowView that triggers the error? Did you import the package? import XCPlayground?

    Thibault

    Thursday, June 5, 2014 at 6:20 pm #
  8. Thibault Imbert wrote:

    Hi Andrey,

    Why should I not talk about something that I find exciting for us (Flash developers) here? I actually want to show you new things because I think Swift is progress and makes iOS development more fun and approachable using a language that’s better than AS3. Objective-C was not appealing to me, Swift is, that I see as a mix between modern ES6, F# and C#/AS3.

    I did not sell my soul. As a developer, you have to adapt to changes, where the industry is going. I will always have Flash in my heart, this is where I come from and I think Swift/Playgrounds is fun and is the future of iOS development, I hope the next tutorials I will post will get you more interested :)

    Thibault

    Thursday, June 5, 2014 at 6:32 pm #
  9. Thibault Imbert wrote:

    Hi Radu,

    That would be awesome. I don’t think these platforms will be supported out of the box, but I trust the community to be creative about that and maybe find solutions. I will keep an eye out and keep you guys posted.

    Thibault

    Thursday, June 5, 2014 at 6:37 pm #
  10. Gordon wrote:

    To Nick,

    the missing XCPlayground happens if you are trying to run the code in an iOS playground, rather than an OS X Playground. This swift code sample is OS X specific.

    Friday, June 6, 2014 at 4:09 am #
  11. Thibault Imbert wrote:

    Hi Gordon,

    Indeed, and I added a note about this to avoid confusion. I am still wondering how to use Playgrounds for iOS, I can’t find the equivalent of XCPlayground for iOS.

    Thibault

    Friday, June 6, 2014 at 5:44 am #
  12. Andrey wrote:

    Hi Thibault,
    I didn’t know that this blog is so iOS oriented, excuse me for my bad notice.

    It’s clear now that everything’s going towards Apple and their iOS, and that’s the exact reason I’m so unhappy.
    Some of the old Flash developers still use it as a technology NOT only for iOS development, but I truly see this is the way for both Apple and Adobe to go now :)

    I will be more than happy if they announce they got some agreement and sold Flash to Apple :P

    Cheers!

    Friday, June 6, 2014 at 4:18 pm #
  13. Mehdadoo wrote:

    @Thibault Imbert
    1.”I think Swift is progress and makes iOS development more fun and approachable using a language that’s better than AS3″
    2.”As a developer, you have to adapt to changes, where the industry is going.”

    When you worked for Adobe improvements to ActionScript was one of the main concerns of this blog, wasn’t it? And you were doing it nice. But now that you are not working for Adobe, and no one is working on AS next, You are saying how Swift is better than AS3. I am happy with that, as a “business man” (Not’As a developer’ that you are mentioning), it’s OK and you have to go with the flow. I hope you become become super rich!

    Friday, June 6, 2014 at 7:31 pm #
  14. Thibault Imbert wrote:

    Hi Mehdadoo,

    I still work for Adobe, I talk on this blog about the things I am currently excited about. It’s been Flash for 15 years, and now I am having fun with Swift. I don’t think this is going to make me rich, but I am having fun ;)

    Thibault

    Friday, June 6, 2014 at 11:05 pm #
  15. Felix Martinez wrote:

    Go Swift go! exciting times with webGL coming to iOS :D

    Sunday, June 8, 2014 at 12:34 am #
  16. Hey Thibault, I have some free time today so I’m catching up with your articles.
    I’m wondering how you got the osc graph to show up – is Playground automatically watching all ‘var’ assignments, or does it come from the update method ?
    Cheers

    Sunday, June 8, 2014 at 11:00 am #
  17. ferber wrote:

    Ce langage est assez proche de ECMAScript Edition 3. Donc un pseudo clone de l’As3, donc je suis plutôt content, si je dois m’en servir ça me ferra moins de doc à lire.
    Pensez-vous que Apple pourrait introduire ce nouveau langage auprès du w3c comme postulant a la succession du js ? Ou au contraire que ce langage vas être cantonné au périphérique Apple ?
    Merci Mr.

    Sunday, June 8, 2014 at 10:21 pm #
  18. Thibault Imbert wrote:

    Hi Florian,

    To have any variable displayed, just go to the line where your variable is defined/declared and go to the extreme right of the line and click on the little eye icon. It will display a graph with the variable values displayed.

    Thibault

    Sunday, June 8, 2014 at 10:35 pm #
  19. Thibault Imbert wrote:

    Salut ferber,

    Je pense que Swift va rester pour le moment cantonné a la plateforme Apple. Si le compilateur Swift venait à etre open-source, cela ouvrirait la porte a des projets permettant de compiler du Swift pour d’autres plateforme, mais je ne pense pas que ce soit le souhait d’Apple pour le moment.

    Thibault

    Sunday, June 8, 2014 at 10:40 pm #
  20. Thibault Imbert wrote:

    Hi Marcin,

    Unfortunately only for Mac OS for now.

    Thibault

    Wednesday, June 11, 2014 at 1:26 am #
  21. Nick Hanan wrote:

    Hi Thibault,

    Thanks for sharing this playground and commenting it so well. I’m new to Sprite Kit, and this will be very helpful in learning about Sprite Kit while also learning more about Swift.

    Definitely continue writing about Swift.

    Thursday, July 3, 2014 at 9:05 am #
  22. Thibault Imbert wrote:

    Hi Nick,

    My pleasure. Happy this is helpful to you. I will keep writing about it!

    Thibault

    Thursday, July 3, 2014 at 9:14 am #
  23. The code didn’t work for me. I kept on getting errors EXC_BAD_ACCESS on the line of code that assigned the image.

    Thanks to the devforums this issue is solved.

    let sprite = NSImage(contentsOfFile: “/Users/dgwilson/Documents/Shared Playground Data/Spaceship.png”)

    I had to create a Shared Playground Data folder in my Documents folder. The image I’m using goes into that folder. FIXED.

    This is a great Swift example well done. Thank you.

    - David

    Friday, August 15, 2014 at 11:10 pm #