Codementor Events

Extending Classes in Swift

Published Aug 27, 2018Last updated Jul 28, 2021

One of the simpliest things to do in swift is extend the base classes. Whether I'm working in SpriteKit with lots of images and buttons or with AVAudioEngine and AVAudioFiles, I typically extend classes and keep them for future use.

Before extending a class I create a new swift file in the project and name it "Extend-NAMEofCLASS" like: Extend-SKSpriteNode or Extend-Array

My Extend-Array looks like the following because I practically ALWAYS need to rotate through my array:

extension Array {
    func rotate(shift:Int = 1) -> Array {
        var array = Array()
        if (self.count > 0) {
            array = self
            if (shift > 0) {
                for _ in 1...shift {
                    array.append(array.remove(at: 0))
                }
            }
            else if (shift < 0) {
                for _ in 1...abs(shift) {
                    array.insert(array.remove(at: array.count-1),at:0)
                }
            }
        }
        return array
    }
}

Another example would be with SKSpriteNode. I often need to set whether an Sprite is moveable and often want to know where a sprite was originally placed so I add two variable to my Sprites. And, sometimes I don't want to have to type "self.origin = self.position" so I added a setOrigin function to do so:

import GameKit

extension SKSpriteNode {
    var moveable: Bool = false
    var origin: CGPoint = CGPoint(x:0,y:0)
    
    func setOrigin() {
        self.origin = self.position
    }
}

For a basic overview of extending classes plus enum and struct, check out:
Ray Wnderlich's site "Getting to know Enums, Structs and Classes in Swift"
Enjoy!

Discover and read more posts from Brian Becker
get started
post commentsBe the first to share your opinion
Show more replies