Abstract classes in Swift Language

97,420

Solution 1

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

Solution 2

Note that this answer is targeted at Swift 2.0 and above

You can achieve the same behaviour with protocols and protocol extensions.

First, you write a protocol that acts as an interface for all the methods that have to be implemented in all types that conform to it.

protocol Drivable {
    var speed: Float { get set }
}

Then you can add default behaviour to all types that conform to it

extension Drivable {
    func accelerate(by: Float) {
        speed += by
    }
}

You can now create new types by implementing Drivable.

struct Car: Drivable {
    var speed: Float = 0.0
    init() {}
}

let c = Car()
c.accelerate(10)

So basically you get:

  1. Compile time checks that guarantee that all Drivables implement speed
  2. You can implement default-behaviour for all types that conform to Drivable (accelerate)
  3. Drivable is guaranteed not to be instantiated since it's just a protocol

This model actually behaves much more like traits, meaning you can conform to multiple protocols and take on default implementations of any of them, whereas with an abstract superclass you're limited to a simple class hierarchy.

Solution 3

I think this is the closest to Java's abstract or C#'s abstract:

class AbstractClass {

    private init() {

    }
}

Note that, in order for the private modifiers to work, you must define this class in a separate Swift file.

EDIT: Still, this code doesn't allow to declare an abstract method and thus force its implementation.

Solution 4

The simplest way is to use a call to fatalError("Not Implemented") into the abstract method (not variable) on the protocol extension.

protocol MyInterface {
    func myMethod() -> String
}


extension MyInterface {

    func myMethod() -> String {
        fatalError("Not Implemented")
    }

}

class MyConcreteClass: MyInterface {

    func myMethod() -> String {
        return "The output"
    }

}

MyConcreteClass().myMethod()

Solution 5

After I struggled for several weeks, I finally realized how to translate a Java/PHP abstract class to Swift:

public class AbstractClass: NSObject {

    internal override init(){}

    public func getFoodToEat()->String
    {
        if(self._iAmHungry())
        {
            return self._myFavoriteFood();
        }else{
            return "";
        }
    }

    private func _myFavoriteFood()->String
    {
        return "Sandwich";
    }

    internal func _iAmHungry()->Bool
    {
        fatalError(__FUNCTION__ + "Must be overridden");
        return false;
    }
}

public class ConcreteClass: AbstractClass, IConcreteClass {

    private var _hungry: Bool = false;

    public override init() {
        super.init();
    }

    public func starve()->Void
    {
        self._hungry = true;
    }

    public override func _iAmHungry()->Bool
    {
        return self._hungry;
    }
}

public protocol IConcreteClass
{
    func _iAmHungry()->Bool;
}

class ConcreteClassTest: XCTestCase {

    func testExample() {

        var concreteClass: ConcreteClass = ConcreteClass();

        XCTAssertEqual("", concreteClass.getFoodToEat());

        concreteClass.starve();

        XCTAssertEqual("Sandwich", concreteClass.getFoodToEat());
    }
}

However I think Apple did not implement abstract classes because it generally uses the delegate+protocol pattern instead. For example the same pattern above would be better done like this:

import UIKit

    public class GoldenSpoonChild
    {
        private var delegate: IStomach!;

        internal init(){}

        internal func setup(delegate: IStomach)
        {
            self.delegate = delegate;
        }

        public func getFoodToEat()->String
        {
            if(self.delegate.iAmHungry())
            {
                return self._myFavoriteFood();
            }else{
                return "";
            }
        }

        private func _myFavoriteFood()->String
        {
            return "Sandwich";
        }
    }

    public class Mother: GoldenSpoonChild, IStomach
    {

        private var _hungry: Bool = false;

        public override init()
        {
            super.init();
            super.setup(self);
        }

        public func makeFamilyHungry()->Void
        {
            self._hungry = true;
        }

        public func iAmHungry()->Bool
        {
            return self._hungry;
        }
    }

    protocol IStomach
    {
        func iAmHungry()->Bool;
    }

    class DelegateTest: XCTestCase {

        func testGetFood() {

            var concreteClass: Mother = Mother();

            XCTAssertEqual("", concreteClass.getFoodToEat());

            concreteClass.makeFamilyHungry();

            XCTAssertEqual("Sandwich", concreteClass.getFoodToEat());
        }
    }

I needed this kind of pattern because I wanted to commonize some methods in UITableViewController such as viewWillAppear etc. Was this helpful?

Share:
97,420

Related videos on Youtube

kev
Author by

kev

Updated on February 24, 2021

Comments

  • kev
    kev over 3 years

    Is there a way to create an abstract class in the Swift Language, or is this a limitation just like Objective-C? I'd like to create a abstract class comparable to what Java defines as an abstract class.

    • jboi
      jboi almost 8 years
      Do you need the full class to be abstract or just some methods in it? See the answer here for single methods and properties. stackoverflow.com/a/39038828/2435872 . In Java you can ave abstract classes, that have none of the methods abstract. That special feature is not provided by Swift.
  • kev
    kev about 10 years
    Do you have any idea how to set a protocol property, or is that not possible?
  • Steve Waddicor
    Steve Waddicor about 10 years
    Protocols don't have properties. They define an interface, they don't implement it. A protocol can require the class it's applied to to have the property though.
  • drewag
    drewag about 10 years
    protocol Animal { var property : Int { get set } }. You can also leave out the set if you don't want the property to have a setter
  • Jens Wirth
    Jens Wirth about 10 years
    @KevinHarrington: As drewag said, it's important to keep mind that you MUST use "get" or "get set". Otherwise it won't compile.
  • A'sa Dickens
    A'sa Dickens almost 10 years
    Protocols are interfaces C: in c#
  • Dmitry
    Dmitry over 9 years
    @David This is not true. As of 8 version Java interfaces have default methods which carry implementation
  • Mazyod
    Mazyod over 9 years
    A main difference to mention is that abstract classes can inherit from regular classes, while protocols can't. Also, the fact that you can conform to multiple protocols and only inherit one abstract class .. Apples and Oranges, really.
  • MLQ
    MLQ over 9 years
    Still, this doesn't force a subclass to override a function while also having a base implementation of that function in the parent class.
  • Teejay
    Teejay over 9 years
    In C#, if you implement a function in an abstract base class, you're not forced to implement it in its subclasses. Still, this code doesn't allow you to declare an abstract method in order to force override.
  • Josh Woodcock
    Josh Woodcock about 9 years
    there's two ways to implement abstract-class-like behavior in swift. I have provided both below.
  • Mario Zannone
    Mario Zannone almost 9 years
    I think this wwdc video is even more relevant
  • Scott H
    Scott H almost 9 years
    @MarioZannone that video just blew my mind and made me fall in love with Swift.
  • Richard Topchii
    Richard Topchii over 8 years
    Still, there is not always a possibility to extend some protocols, for example, UICollectionViewDatasource. I would like to remove all the boilerplate and encapsulate it in separate protocol/extension and then re-use by multiple classes. In fact, the template pattern would be perfect here, but...
  • Морт
    Морт over 8 years
    This does not provide any guarantees and/or checks. Blowing up during runtime is a bad way of enforcing rules. It's better to have the init as private.
  • Angad
    Angad over 8 years
    Also, it would help if both your examples were on the same use-case. GoldenSpoonChild is a slightly confusing name, especially given that Mother seems to be extending it.
  • Cristik
    Cristik over 8 years
    Abstract classes should also have support for abstract methods.
  • Javier Cadiz
    Javier Cadiz over 8 years
    Lets say that ConcreteClass subclass that AbstractClass. How do you instantiate ConcreteClass ?
  • Teejay
    Teejay over 8 years
    ConcreteClass should have a public constructor. You probably need a protected constructor in AbstractClass, unless they are in the same file. As per what I remember, protected access modifier does not exist in Swift. So the solution is to declare ConcreteClass in the same file.
  • Alexey Yarmolovich
    Alexey Yarmolovich over 8 years
    @Cristik I showed main idea, it's not complete solution. This way you can dislike 80% of answers because they are not detailed enough for your situation
  • Cristik
    Cristik over 8 years
    @AlexeyYarmolovich who says I'm not disliking 80% of the answers? :) Joking aside, I was suggesting that your example can be improved, this will help other readers, and will help you by getting upvotes.
  • Slipp D. Thompson
    Slipp D. Thompson over 7 years
    Your example code doesn't demonstrate dynamic dispatch, and your “When logSalary is called on the …” explanation is describing polymorphism, which Swift certainly has for class inheritance, but not for protocol extensions. TL;DR: If you turn protocol Employee & extension Employee into a class Employee and turn SoftwareEngineer into a class SoftwareEngineer : Employee, your example prints ”overridden\noverridden\n”. | Also, Swift does indeed have dynamic dispatch — when you make your class inherit from NSObject. Then it uses the Obj-C runtime, and thus dynamic dispatch.
  • Josh Woodcock
    Josh Woodcock over 7 years
    @Angad The delegate pattern is the same use case, however its not a translation; it's a different pattern so it must take a different perspective.
  • Mike Taverne
    Mike Taverne about 7 years
    This is a great answer. I didn't think it would work if you called (MyConcreteClass() as MyInterface).myMethod() but it does! The key is including myMethod in the protocol declaration; otherwise the call crashes.
  • Mike Taverne
    Mike Taverne about 7 years
    If you just add func logSalary() to the Employee protocol declaration, the example prints overridden for both calls to logSalary(). This is in Swift 3.1. Thus you get the benefits of polymorphism. The correct method is called in both cases.
  • Gerd Castan
    Gerd Castan over 6 years
    You can't overwrite ˚accelerate˚ in ˚Car˚. If you do, the implementation in ˚extentsion Driveable˚ is still called without any compiler warning. Very unlike a Java abstract class
  • IluTov
    IluTov over 6 years
    @GerdCastan True, protocol extensions do not support dynamic dispatch.
  • Mark A. Donohoe
    Mark A. Donohoe over 6 years
    The rule about dynamic dispatch is this... if the method is defined only in the extension, then it's statically dispatched. If it's also defined in the protocol you're extending, then it's dynamically dispatched. No need for Objective-C runtimes. This is pure Swift behavior.
  • jreft56
    jreft56 about 5 years
    No abstract classes in Swift ? Documentation says: "Operation An abstract class that represents the code and data associated with a single task"
  • Dave
    Dave over 2 years
    The only problem with this advice is the a Swift protocol is the analogue of neither Java's interface nor abstract class. Specifically Swift protocols are hamstrung by Swift's terrible generics implementation. Try specifying a protocol that extends Hashable and feel the pain.