The difference between ‘class func’ and ‘static func’ in Swift

Hello, my people, Leo here. Today I learned that you have two ways to declare functions on the class/struct level and it’s using the keywords above and the post today is about the difference between class func and static func.

Knowing the difference between those two is very important for any iOS because it has consequences in your code base that you should be aware of. The uses of class/struct level structures are way beyond just helpers, they can leverage your code to another level. Writing really expressive APIs that other developers have an easy time using is a gift for your coworkers and for your future self.

If you are ready to know the difference between class func and static func, let’s go!

Difference between class func and static func

Let’s check the code below:

static func foo(){}

class func bar(){}

But what’s the difference?

The main difference is static is for static functions of structs and enums, and class for classes and protocols.

From Chris Lattner the father of Swift.

We considered unifying the syntax (e.g. using “type” as the keyword), but that doesn’t actually simply things. The keywords “class” and “static” are good for familiarity and are quite descriptive (once you understand how + methods work), and open the door for potentially adding truly static methods to classes. The primary weirdness of this model is that protocols have to pick a keyword (and we chose “class”), but on balance it is the right tradeoff.

But another distinction is that class functions are dynamically dispatched and can be overridden by subclasses. As the snippet below shows:

 

class Plane {
    class func fly() {
        print("fly around")
    }
}

class PrivateJet: Plane {
    override class func fly() {
        print("this is awesome")
    }
}

var x: Plane = PrivateJet()
type(of: x).fly() //this prints 'this is awesome'
x = Plane()
type(of: x).fly() // this prints 'fly around'

Because of the nature of polymorphism, you can write the code above and it will work fine!

Summary

Today we learned the difference between class func and static func in Swift.

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits: image

Share this post:

Related posts

Sponsor