Nonoku - Composition

Since I’m using the same background in a bunch of places I want to make it really easy to re-use. I could make a sub-class of UIViewController which implements the functionality. I’m not a fan of that, if it can be avoided. These things have tendency to grow. I could also create a static class method to return the background SKNode. That’s a little better but that’s just a form of composition and Swift actually gives us a nice way to implement this with Protcols and Extensions.

I start by moving declaring the function used for creating the background in a protocol. I’ll call it BackgroundProtocol because I’m awful at names. That’s easy to change later if I decide to add more functionality anyway.

protocol BackgroundProtocol {
    func createBackground(size: CGSize) -> SKNode

I can add that protocol to other classes and they’ll have the createBackground(size:) function available to them. Using an extension I can then create a default implementation (by striking coincidence, that’s the code I already had for this).

extension BackgroundProtocol {
    func createBackground(size: CGSize) -> SKNode {         
        let node = SKEffectNode()
        // snip ...
        return node

Now I can add that to all the views in my app and they can just call it to get the functionality. And, of course, it can be overridden if needed.

class MainMenuViewController: UIViewController, BackgroundProtocol {
    override func viewDidLoad() {
        let spriteView = (view as? SKView)!
        let scene = SKScene(size: view.bounds.size)
        scene.addChild(createBackground(size: scene.size))