Where To Put Reusable Functions In Swift

By Eddy Chung

Reusable functions are a good coding practice and follow the DRY (Don’t Repeat Yourself) principle. The question is, where to put these functions in Swift?

Static Functions In A Helper Class

This is probably the most common option. Most developers are used to putting helper methods as static functions in a helper class.

class Helper {
    static func reusableFunction() {
        // Do stuff here
    }
}

You can then call this function like so:

Helper.reusableFunction()

The major pro of this method is that most developers will understand your code while reading it. This pattern is prevalent not only in Swift, but most common languages.

The con is if you need to pass parameters often to your Reusable functions, this can be redundant to type in code.

For example:

class Helper {
    static func helpMe(a: AClass, b: BClass, c: CClass) {
        // do stuff here ...
    }

    static func sendHelpSignal(a: AClass, b: BClass, c: CClass) {
        // do stuff here ...
    }
}

Then to call the above functions you’ll have to do this:

Helper.helpMe(a: aInstance, b: bInstance, c: cInstance)
Helper.sendHelpSignal(a: aInstance, b: bInstance, c: cInstance)

If you find yourself needing the same parameters to your helper functions, you should consider a different design pattern.

Protocol Extensions

This is my preferred method of creating helper functions.

protocol Helper {
}

extension Helper {
    func reusableFunction() {
        // do stuff here ...
    }
}

To call this function, your class should extend helper like so:

class ViewController: UIViewController, Helper {
    override func viewDidLoad() {
        super.viewDidLoad()
        reusableFunction()
    }
}

The main con of this approach is it’s less common of a pattern. Developers coming from another language may be initially confused.

The main pro is that protocols can access properties of the class, if they’re defined in the protocol. For example:

protocol Helper {
    var viewModel: CustomViewModel
}

extension Helper {
    func printMessage() {
        print(viewModel.message)
    }
}

How to use it:

class ViewController: UIViewController, Helper {
    var viewModel: CustomViewModel

    override func viewDidLoad() {
        super.viewDidLoad()
        printMessage()
    }
}

Best of luck with your code and remember don’t repeat yourself!

If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts