Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Create utility methods as static class or regular functions? [duplicate]

Tags:

swift

Coming from Java we often create utility methods as:

class Util {
    public static doSomething(...) {
        ....
    }
}

In Swift it seems you can do the same with static func

class Util {
     static func doSomething(...) {
         ....
     }
}

But then you can also just do a stand alone function in Swift which is not not within a class.

func doSomething(...) {
      ....
}

What is the best practice? Is this subjective or there is a reason why you must pick one or the other approach?

like image 338
Marcus Leon Avatar asked Oct 19 '22 12:10

Marcus Leon


1 Answers

It is largely subjective and there is no reason why you must pick one over the other.

That being said, some people favor the static method approach for organizational reasons, or as a form of namespacing. For example, using the static method approach also allows you to have a method ClassA.doSomething() and a method named ClassB.doSomething().

like image 94
Aaron Rasmussen Avatar answered Oct 21 '22 04:10

Aaron Rasmussen