Class vs Static vs Final Static

It would be good option to attach variables or functions to Class instead of instance in some cases. We have several options to do this; class, static or final class.

Let’s try an example to understand what they are and their differences.

class Tax {
    
    static func calculateTax() -> Double {
        5 * calculateTaxRatio() + addBonusIncomeTax()
    }
    
    class func calculateTaxRatio() -> Double {
        10
    }
    
    final class func addBonusIncomeTax() -> Double {
        2.5
    }
}

We have a Tax class and several functions.
Firstly, let’s talk about first two functions, static and class. Both of them is attached Tax Class which means you can call them without an instance. That also means, they are in memory from the beginning of application to end.

!There is a Difference.
The difference is that subclasses can override class methods; they cannot override static methods.

Thanks to final keyword, “final class” is acting like static keyword as well.

class TeacherTax: Tax {
    
    override class func calculateTaxRatio() -> Double {
        5
    }
}

If you try to override static function, complier will warn you as below.
Cannot override static method!

Bu if you try to override “final class” function, complier’s message is:
Class method overrides a ‘final’ class method!

Variables

We can consider two property type which are computed or stored. In Swift, you cannot create a class var stored property, you can only create computed property or you have to use static keyword to be able to create stored one.

class var taxRatio: Double = 3 //Error: Class stored properties not supported in classes; did you mean 'static'?

static var taxRatio: Double = 3 // Legal

On the other hand, keywords’ behavior in computed properties as same as in functions.

static var taxRatio: Double { 5 } // Not overridable
    
class var taxInstallCount: Int { 3 } // Overridable
    
final class var participantCount: Int { 5 } // Not overridable

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s