Home » Software Development » Example of using extensions in Swift
About Pascal Alma

Pascal is a senior JEE Developer and Architect at 4Synergy in The Netherlands. Pascal has been designing and building J2EE applications since 2001. He is particularly interested in Open Source toolstack (Mule, Spring Framework, JBoss) and technologies like Web Services, SOA and Cloud technologies. Specialties: JEE, SOA, Mule ESB, Maven, Cloud Technology, Amazon AWS.
   
Example of using extensions in Swift
Posted by: Pascal Alma  in Software Development January 21st, 2016

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:
01
let π = CGFloat(M_PI)
02
 
03
extension SKAction {
04
    static func oscillate(amplitude a: CGFloat, timePeriod t: CGFloat, midPoint: CGPoint) -> SKAction {
05
        let action = SKAction.customActionWithDuration(Double(t)) { node, currentTime in
06
            let displacement = a * sin(2 * π * currentTime / t)
07
            node.position.y = midPoint.y - displacement
08
        }
09
        return action
10
    }
11
}
You can use the extension and apply it to a SpriteNode in your GameScene.swift for example like this:
01
import SpriteKit
02
 
03
class GameScene: SKScene {
04
     
05
    let ball = SKSpriteNode(imageNamed: "ball")
06
     
07
    override func didMoveToView(view: SKView) {
08
        /* Setup your scene here */
09
        backgroundColor = SKColor.clearColor()
10
         
11
        ball.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
12
         
13
        addChild(ball)
14
         
15
        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width)
16
        ball.physicsBody?.restitution = 0.0
17
        ball.physicsBody?.linearDamping = 0.0
18
        ball.size = CGSize(width: 100, height: 100)
19
        ball.physicsBody?.affectedByGravity = false
20
         
21
        let oscillate = SKAction.oscillation(amplitude: size.height/4, timePeriod: 8, midPoint: ball.position)
22
        ball.runAction(SKAction.repeatActionForever(oscillate))
23
    }
24
}
As you can see I ignored the gravity and other ‘forces’ on the object.
