Static vs Class vs Global Functions in Swift

Hemant Soni
2 min readFeb 18, 2021

--

Functions are self-contained chunks of code that perform a specific task. There are multiple ways to write functions in Swift.

Static Functions:

Static functions are invoked by the class/struct itself, not by an instance. This makes it simple to invoke utility functions.

class AppUtility {
static func appUtility() {
}
}

We can access static function as AppUtility.appUtility()

Note: Static functions can not be overridden and static is same as class final..

Class Functions:

Class functions (not instance methods) are also static functions but they can be overridden by subclasses unlike static functions.

class AppUtility{
class func appUtility(){
print("Inside AppUtility")
}
}
class AppOtherUtility: AppUtility{
override class func appUtility(){
print("Inside AppOtherUtility")
}
}

We can access them similar to static functions as AppUtility.appUtility() and AppOtherUtility.appUtility().

we can call the appUtility method as AppUtility.appUtility() and AppOtherUtility.appUtility()

Global Functions:

If the function is not in class or structure and it is independent in the project. The global functions can be kept in a separate file that we can import into any project as per the requirement.

func appUtility() {
}

We can just access them as appUtility() anywhere in the project.

Note: In case of static functions, if we access one of the static member, entire class gets loaded in memory. But in case of global function, only that particular function will be loaded in memory.

Thank you for reading

I hope it will be useful for you. Please let me know your thoughts and opinions :). If you enjoyed it, feel free to hit the clap button below 👏 to help others find it!

--

--

Hemant Soni
Hemant Soni

Written by Hemant Soni

Sr. iOS Application Developer

No responses yet