Example of using extensions in Swift

Recently I needed a image in my iOS app that was oscillating. I ran into an example of Swift code that showed how to do it and it was actually quite easy to do (for the theory behind the formula see this). The code makes use of the ‘extension’ feature in Swift. This is a really cool feature in Swift. The feature allows you to extend the functionality of a class without having to extend the class (like you would do in Java for instance). For a basic example of the feature see this example.
In my example the feature is used to extend the functionality of the SKAction class, another cool thing in the iOS SpriteKit library.

The extension looks like this:

let π = CGFloat(M_PI)

extension SKAction {
    static func oscillate(amplitude a: CGFloat, timePeriod t: CGFloat, midPoint: CGPoint) -> SKAction {
        let action = SKAction.customActionWithDuration(Double(t)) { node, currentTime in
            let displacement = a * sin(2 * π * currentTime / t)
            node.position.y = midPoint.y - displacement
        return action

You can use the extension and apply it to a SpriteNode in your GameScene.swift for example like this:

import SpriteKit

class GameScene: SKScene {
    let ball = SKSpriteNode(imageNamed: "ball")
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        backgroundColor = SKColor.clearColor()
        ball.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width)
        ball.physicsBody?.restitution = 0.0
        ball.physicsBody?.linearDamping = 0.0
        ball.size = CGSize(width: 100, height: 100)
        ball.physicsBody?.affectedByGravity = false
        let oscillate = SKAction.oscillation(amplitude: size.height/4, timePeriod: 8, midPoint: ball.position)

As you can see I ignored the gravity and other ‘forces’ on the object.
This results in the following behaviour:

About Pascal Alma

Pascal is a senior software developer and architect. Pascal has been designing and building applications since 2001. He is particularly interested in Open Source toolstack (Mule, Spring Framework, JBoss) and technologies like Web Services, SOA and Cloud technologies. Lately he is having great fun by building iOS apps with Swift. Specialties: JEE AWS XML/XSD/XSLT Web Services/SOA Mule ESB/ WSO2 ESB Maven Cloud Technology Swift/ iOS
This entry was posted in iOS, Swift and tagged , . Bookmark the permalink.