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)
        
        addChild(ball)
        
        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)
        ball.runAction(SKAction.repeatActionForever(oscillate))
    }
}

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

About Pascal Alma

Pascal is a senior IT consultant and has been working in IT since 1997. He is monitoring the latest development in new technologies (Mobile, Cloud, Big Data) closely and particularly interested in Java open source tool stacks, cloud related technologies like AWS and mobile development like building iOS apps with Swift. Specialties: Java/JEE/Spring Amazon AWS API/REST Big Data Continuous Delivery Swift/iOS
This entry was posted in iOS, Swift and tagged , . Bookmark the permalink.