Abstract classes in Swift Language

There are no abstract classes in Swift (just like Objective-C). Your best bet is going to be to use a Protocol, which is like a Java Interface.

With Swift 2.0, you can then add method implementations and calculated property implementations using protocol extensions. Your only restrictions are that you can’t provide member variables or constants and there is no dynamic dispatch.

An example of this technique would be:

protocol Employee {
    var annualSalary: Int {get}
}

extension Employee {
    var biweeklySalary: Int {
        return self.annualSalary / 26
    }

    func logSalary() {
        print("$\(self.annualSalary) per year or $\(self.biweeklySalary) biweekly")
    }
}

struct SoftwareEngineer: Employee {
    var annualSalary: Int

    func logSalary() {
        print("overridden")
    }
}

let sarah = SoftwareEngineer(annualSalary: 100000)
sarah.logSalary() // prints: overridden
(sarah as Employee).logSalary() // prints: $100000 per year or $3846 biweekly

Notice that this is providing “abstract class” like features even for structs, but classes can also implement the same protocol.

Also notice that every class or struct that implements the Employee protocol will have to declare the annualSalary property again.

Most importantly, notice that there is no dynamic dispatch. When logSalary is called on the instance that is stored as a SoftwareEngineer it calls the overridden version of the method. When logSalary is called on the instance after it has been cast to an Employee, it calls the original implementation (it doesn’t not dynamically dispatch to the overridden version even though the instance is actually a Software Engineer.

For more information, check great WWDC video about that feature: Building Better Apps with Value Types in Swift

Leave a Comment