I want to create a Helper.swift
file to add some functions/methods that are useful in different parts of my app.
I was wondering what is the best practice (if there is one): create a class and only create type methods or just create functions?
Here's a simple rule of thumb: if the code acts upon a single instance of an object, use a method. Even better: use a method unless there is a compelling reason to write it as a function.
A method, like a function, is a set of instructions that perform a task. The difference is that a method is associated with an object, while a function is not.
A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.
Method and a function are the same, with different terms. A method is a procedure or function in object-oriented programming. A function is a group of reusable code which can be called anywhere in your program. This eliminates the need for writing the same code again and again.
I would generally lean towards using a type methods on an appropriately named type, in order to give your helper methods context and avoid polluting the global namespace.
In Swift, structs are an ideal candidate for this sort of construct:
struct Helper {
static func helpfulMethod() { ... }
}
I also use embedded structs with static constants quite liberally in my top level types in order to group related constants within my code.
In writing custom Swift types, you should generally consider using structs first, and only resort to classes when inheritance, reference semantics (as opposed to the implicit copying with value semantics) or ownership semantics (unowned
/weak
) are required. In this case, your utility functions will be stateless, and there is no inheritance to speak of, so a struct should really be preferred over a class.
I would argue that in general, the Swift language is moving away from global functions in favour of the implicit namespacing provided by types (and protocols/generics). But it's still largely a matter of style/personal preference, and for something as simple as a utility function it's of little consequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With