Swift API for the Flash Guy

flashhistory

Flash.

The ‘f’ word. At least it feels like a dirty word right?

Flash really spiralled out of fashion since Steve Jobs’ famous “Thoughts on Flash” open letter five years ago. Wired posted an article last month titled “Flash.Must.Die”, the Facebook security chief called for its termination, the Occupy Flash movement called for us to eliminate it from our browsers, while the big name browsers themselves starting eliminating it for us.

Well known and respected Flash evangelists took to the wilderness to escape the public Flash-hunt. Others went underground, transitioning to HTML5 and JavaScript, Android or iOS, while hiding their Flash skills deep in their CVs and just occasionally – when they’re sure no-one’s looking – opening up Flash as a little guilty pleasure.

Flash developers who stuck by Flash face the possibility of career skills becoming redundant. You face two options – wait until it’s in demand again (Cobol style!) or reskill now!

I’ll admit my decision a couple of years ago to reskill in Swift wasn’t an easy decision at the time. It felt like I was leaving behind my expertise and starting over.

I have a Flash developer friend Paul, who tells me: “Yeah things are pretty bleak on the Flash front… I am very tempted to get stuck into Swift but have a fear at the back of my head in 5 years time it will become redundant just like happened with Authorware, Director, Flash etc… My other fear is it is too steep a learning curve.”

If you’ve found your way here as a Flash guy, on the run, trying other things and thinking about getting into Swift but perhaps you’re scared, confused, fearful of change, don’t worry, you’re in a safe space. And this is the tutorial for you…

SwiftAPIfortheFlashGuy

In this tutorial, we’re going to port an ActionScript game called “Flashy Bird” to Swift. You can download the Flash source code for Flashy Bird here. Go ahead, download and run it to see what we’re dealing with.

For simplicity and to keep everything feeling as familiar as possible as we move into new territory, we’re going to use a framework I’ve built called “ActionSwift3”. This framework enables you to use some of the familiar AS3 API, but from built on top of what’s called the `SpriteKit` framework, within Swift.

In ActionSwift3 you’ll find familiar classes such as `MovieClip`, `Sprite`, `SimpleButton`, `TextField`, `Sound`, `EventDispatcher`, the list goes on.

In addition to the API, ActionSwift3 has incorporated much of the syntax and data types of ActionScript. For example, you can use ActionScript’s `int`, `Number`, `Boolean`, as they are simply interpreted as Swift datatypes `Int`, `CGFloat` and `Bool`. Similarly, ActionScript’s `trace’ is simply interpreted as Swift’s global function `print`. You can find more info on ActionSwift3 at its github page and API documentation here.

Now, all of this is intended to help make the transition easier for you initially in a familiar environment and I imagine in time you’ll challenge yourself to become familiar with Swift classes, datatype names and approaches, and potentially leave ActionSwift3 behind. But for now, let’s see how easy it is to port an ActionScript project over to Swift.

Create a new project

If you haven’t downloaded Xcode yet, go ahead and do that, you can find it in the App Store. Open up Xcode and familiarize yourself with the interface.

Go to File>New>Project, iOS>Application>Game and fill in the project fields. Be sure to select Swift and SpriteKit, select Next, choose a path, select Next and your project is ready.

createProject

A little housekeeping before we start. The template automatically set up a GameScene.swift and GameScene.sks(sprite kit scene) file. You can go ahead and delete these and select ‘Move to Trash’. Now in the GameViewController file, you can replace everything with a more bare bones approach:

import SpriteKit

class GameViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func shouldAutorotate() -> Bool {
        return false
    }
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .Portrait
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

Before we get too deep into coding, quickly set up the same resources used in the Flash file. Here are the resources. Drag the audio files to the `FlappySwift` group, and ensure ‘Copy items if needed’ is checked. Select ‘New Group from Selection’, and purely to keep your files organized, group the audio into a group named ‘Audio’.

new group

Next drag in the ‘images.atlas’ folder into the ‘FlappySwift’ group. This time, this isn’t just for organizational purposes and the folder name isn’t random. Xcode automagically creates a texture atlas for folders with the extension `atlas`, and the `images.atlas` folder is the default texture atlas. Texture atlases are more commonly known as sprite sheets in Flash.

CocoaPods

CocoaPods is a tool for managing third party libraries in your Xcode project. You’re going to use it to import the ActionSwift3 library to the project. Follow the CocoaPods installation instructions here.

Now you have CocoaPods installed, install ActionSwift3:

  1. Close your FlappySwift project in Xcode.
  2. Create a file in your main FlappySwift folder(not the inner folder) called ‘Podfile’, and include the following:
    source 'https://github.com/CocoaPods/Specs.git'
    use_frameworks!
    platform :ios, '8.0'
    pod 'ActionSwift3'
    
  3. From the Finder, drag the whole FlappySwift folder(not the inner folder) to Terminal, and type in `pod install`. Give it a few minutes. In addition to installing ActionSwift3 it’s building what’s called a ‘workspace’ for your project that you will need to open from here-on instead of your ‘project’ file.
  4. That’s it! You should now find a ‘`FlappySwift.xcworkspace` file in your project folder. Open it up.

Now, you’re set to use ActionSwift3!

Find your `GameViewController.swift` file again, and add import ActionSwift3 to the import statements. You might need to rebuild your project again(⌘ B) for Xcode to recognize this module. Now at the bottom of the viewDidLoad method, add let stage = Stage(self.view as! SKView) and you’re ready to start adding children to Stage, ActionSwift3 style!

Have a look at the `GameViewController.swift` in the github example app here, to see what sort of familiar classes are available to you, and how you can build up a simple app in ActionSwift3.

Create a Swift class

Let’s return to Flappy Bird now, to look at building something a little more complex in ActionSwift3.

Start off by creating a Swift file to represent the ‘root’ class, called FlappyBird.swift.

Select File>New>File, CocoaTouch Class(which actually means you’re creating a class that subclasses another class) and Next. Type `FlappyBird` in the Class field, subclass `MovieClip` and Language `Swift`.

Now a skeleton of your FlappyBird class should auto-generate. The first thing you may notice is there are no packages. Everything in a target is assumed to be in the same namespace. As ActionSwift3 is stored in a different target, you’ll want to import this target:

import ActionSwift3

…and that’s it! It’s not necessary(nor possible) to import every class.

Do the same for all six classes of the FlappyBird game.

Convert code

Now to convert your code across from ActionScript. Now, much of ActionScript syntax has been ported into ActionSwift3, but there are obviously some obvious differences remain:

  • ; The semi-colon is gone in Swift! In fact, it’s just ignored. You can choose to leave them in, but it’s probably a good idea to start training yourself to leave them out.
  • new The `new` keyword is not necessary to instantiate a class.
  • function->func This is abbreviated as `func` in Swift.
  • this->self `this` is called `self` in Swift.

I would suggest that you perform a find and replace on these syntactic differences before copying over code from ActionScript.

More differences require some finesse, here are some to be wary of:

  • const Constants in Swift are defined with `let`.
  • extends In Swift classes are subclassed using a colon rather than the keyword ‘extends’
  • init The constructor of a class in Swift is called the initializer. Replace your constructors with just the keyword `init`.
  • strict typing Swift is a type-safe language, meaning that variables must strictly adhere to their data type definition. This even excludes the value of nil – variables must be initialized by the end of the initializer method, or the superclass’s initializer method. (this can take some mental adjustment.)
  • optionals How can a variable contain nil then, I hear you ask – this is achieved through a special datatype called an Optional. An Optional is indicated by a question mark (?) after the definition of the variable.
  • non-implicit type conversion You’ll find when performing arithmetic between integers and floating point numbers. Leading on from its strict typing philosophy, you’ll need to explicitly convert a data type to be able to perform arithmetic between different data types.
  • brackets in if statements In if statements in Swift, round brackets surrounding the condition are optional, and curly brackets around the code block are mandatory(no implicit single line code blocks).
  • Return values of functions Are specified with `->` instead of a colon `:`.
  • for-loops The c-style for-loop is no longer. Instead, either use a for-in loop looping over every element of an array:
var names = ["Craig","Jemaine","Bret"]
for name in names {
  trace(name)
}

Or, if it’s necessary to loop over a range of values, you can instead use a special type called a range:

for i in 0...3 {
  trace(i)
}
  • RIP ++ You can no longer increment or decrement a value with the ++ or — operators. Replace these in your code with the clearer +=1 or -=1 operators.
  • function parameters Whereas in Flash parameters are identified by the order they’re in and have no external name, the default in Swift is that parameters have an external name. Example in Flash:
var array:Array = ["a","b","c","c","e"];
array.splice(3,1,"d");
trace(array); 	//a,b,c,d,e

In ActionSwift3, it’s actually much clearer what’s going on:

var array = ["a","b","c","c","e"]
array.splice(3,deleteCount:1,values:"d")
trace(array) //a,b,c,d,e

You may have noticed the first parameter of splice doesn’t have a parameter name – there is a way in Swift to prevent an obligatory parameter name if it makes more sense, with an underscore before the parameter name in the function definition. eg:

func distanceTo(_ x:Int, _ y:Int)
…
distanceTo(0,10)

ActionSwift3 uses a combination of the Swift and ActionScript approaches. You can read more about function parameters in Swift here.

Well you’ve just skimmed the surface of some technical differences between Swift and ActionScript. If you’d like to know about some more philosophical differences between the two languages, click here.

Feel free to work through the .as files, converting to Swift as you go. In most cases it’s just a case of slight tweaks to syntax. Or – using the magic of github, here’s one I prepared earlier. You’ll need to run `pod install` to install ActionSwift into the project.

So that’s it Flash guy, you’re on your way to becoming a Swift guy.

And Paul, it might be time to update that old superhero costume!

swift

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with: ,
Posted in Flash, Swift
7 comments on “Swift API for the Flash Guy
  1. Thank you Craig,
    it’s an amazing, helpful post.
    Actually, as a 15 years long Flash developer and artist, my reason no to move to Swift is not that it may be redundant one day, but it’s because it is tied to Apple platforms only. I personally consider Apple one of the worse corporations today. This has nothing to do with their products, but with their policies. They invented closed platforms. They invented fees for developers to release their products. They lied to keep their browser experience lame, in order to cut 30% for each piece of rich experience that must go through the store. The most authoritarian, fascist, exploitative company in IT I have ever witnessed. Of course this is a personal opinion, I do not believe in objectivity. But as such, I will not put my effort, creative power and love for quality on a language that will force me to release my creations on Apple stores only.
    All the best for you, and thank you for the generosity in your posts.
    Filippo

    • Thanks for the candour in giving your perspective Pippo, that’s fair enough if you have aversions to the Apple infrastructure! Have you seen by the way that Swift is going open source?
      All the best

      • Interesting. Hopefully it will become a cross-platform development tool. In that case I will start to check it out, since it’s elegance (especially compared to stone-age objective c) it’s evident. So far I keep working in ActionScript for cross-platform apps, and rarely I downgrade myself to JavaScript/Canvas…
        Anyway I am subscribed to your blog, you never know what’s going to happen in the future 🙂

  2. Paul Steven says:

    Thank you Craig – this is a super blog post and has inspired me to give this Swift malarkey a try though I also seem to be dipping my toes in a few other technologies at the same time.

  3. Bookmarked this sick page!!

  4. […] SDK comes with a tutorial for porting your first Flash game, called “Flashy Bird”, into Swift. This is a clever trick: while you remain wrapped in cosy and familiar ActionScript 3 working on […]

Leave a Reply to Swift resources for Flash and ActionScript developers - Easy Native Extensions Cancel reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: