The difference between 'class func' and 'static func' in Swift and why polymorphism matters

Subscribe to my newsletter and never miss my upcoming articles

Hello my people, Leo here.

Today I learned that you have two ways to declare some func on the class/struct level and its using the keywords above.

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 the 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 other distinction is the that class functions are dynamically dispatched and can be overridden by subclasses. Like 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!

Thanks for the reading and... That's all folks!

Comments (2)

Jethro Lorenzo Garcia Lising's photo

Great article!

Do you have any recommendations for starting iOS dev? What path did you take?

Leonardo Maia Pugliese's photo

The path I took was: 100 days of Swift from Paul Hudson and the testing book, after that the interview prep course from Sean Allen, and in between I read lot of articles of swift by Sundell.