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.
-
Do you need the full class to be abstract or just some methods in it? See the answer here for single methods and properties. http://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. – jboi Aug 19 '16 at 12:16
11 Answers
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

- 3
- 2

- 93,393
- 28
- 139
- 128
-
Do you have any idea how to set a protocol property, or is that not possible? – kev Jun 08 '14 at 20:51
-
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. – Steve Waddicor Jun 08 '14 at 20:53
-
3`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 – drewag Jun 08 '14 at 20:55
-
@KevinHarrington: As drewag said, it's important to keep mind that you MUST use "get" or "get set". Otherwise it won't compile. – Jens Wirth Jun 08 '14 at 20:59
-
-
@David This is not true. As of 8 version Java interfaces have [default methods](http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html) which carry implementation – Dmitry Feb 03 '15 at 18:02
-
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. – Mazyod Mar 06 '15 at 20:45
-
there's two ways to implement abstract-class-like behavior in swift. I have provided both below. – Josh Woodcock May 28 '15 at 00:05
-
4I think [this wwdc video](https://developer.apple.com/videos/wwdc/2015/?id=408) is even more relevant – Mario Zannone Jul 08 '15 at 18:15
-
2@MarioZannone that video just blew my mind and made me fall in love with Swift. – Scott H Sep 02 '15 at 23:05
-
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`\n`overridden`\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. – Slipp D. Thompson Jan 31 '17 at 12:39
-
3If 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. – Mike Taverne May 19 '17 at 17:21
-
1The 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. – Mark A. Donohoe Mar 18 '18 at 04:13
-
No abstract classes in Swift ? Documentation says: "Operation An abstract class that represents the code and data associated with a single task" – jreft56 Jun 08 '19 at 08:08
-
The only problem with this advice is the a Swift `protocol` is the analogue of neither Java's `interface` nor `abstract class`. Specifically Swift `protocol`s are hamstrung by Swift's terrible generics implementation. Try specifying a `protocol` that extends Hashable and feel the pain. – Dave Dec 07 '21 at 08:18
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:
- Compile time checks that guarantee that all
Drivable
s implementspeed
- You can implement default-behaviour for all types that conform to
Drivable
(accelerate
) 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.

- 6,807
- 6
- 41
- 103
-
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... – Richard Topchii Oct 06 '15 at 02:37
-
4You 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 – Gerd Castan Nov 18 '17 at 16:45
-
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.

- 7,210
- 10
- 45
- 76
-
4Still, this doesn't *force* a subclass to override a function while also having a base implementation of that function in the parent class. – Matthew Quiros Mar 27 '15 at 06:08
-
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. – Teejay Mar 27 '15 at 10:00
-
Lets say that ConcreteClass subclass that AbstractClass. How do you instantiate ConcreteClass ? – Javier Cadiz Jan 08 '16 at 22:37
-
2ConcreteClass 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. – Teejay Jan 08 '16 at 23:03
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()

- 1,719
- 1
- 13
- 6
-
2This 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 May 19 '17 at 17:07
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?

- 2,683
- 1
- 22
- 29
-
1Also, 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. – Angad Oct 31 '15 at 09:12
-
@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. – Josh Woodcock Feb 05 '17 at 23:57
There is a way for simulating abstract classes using Protocols. This is an example:
protocol MyProtocol {
func doIt()
}
class BaseClass {
weak var myDelegate: MyProtocol?
init() {
...
}
func myFunc() {
...
self.myDelegate?.doIt()
...
}
}
class ChildClass: BaseClass, MyProtocol {
override init(){
super.init()
self.myDelegate = self
}
func doIt() {
// Custom implementation
}
}

- 111
- 1
- 4
One more way how you can implement abstract class is to block initializer. I've done it this way:
class Element:CALayer { // IT'S ABSTRACT CLASS
override init(){
super.init()
if self.dynamicType === Element.self {
fatalError("Element is abstract class, do not try to create instance of this class")
}
}
}

- 37
- 2
-
4This 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. – Морт Oct 29 '15 at 11:15
-
-
@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 – Alexey Yarmolovich Jan 11 '16 at 08:06
-
1@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. – Cristik Jan 11 '16 at 08:50
It's a really old question but still… Here's a snippet of actual code that compiles on Swift 5.2 and works as intended:
protocol Context {
init() throws
func out(_ aStr: String) throws
// Other stuff
}
class AbstractContext: Context {
required init() throws {
if Self.self === AbstractContext.self {
preconditionFailure("Call to abstract method \(Self.self).\(#function)")
}
}
func out(_ aStr: String) throws {
preconditionFailure("Call to abstract method \(Self.self).\(#function)")
}
// Other stuff
}
class CompileContext: AbstractContext {
required init() throws {}
override func out(_ aStr: String) throws {
print(aStr)
}
// Other stuff
}
And here's what I get once I remove CompileContext.out
:
Fatal error: Call to abstract method CompileContext.out(_:): file swiftpg/contexts.swift, line 28

- 81
- 2
With the limitation of no dynamic dispatch, you could do something like this:
import Foundation
protocol foo {
static var instance: foo? { get }
func prt()
}
extension foo {
func prt() {
if Thread.callStackSymbols.count > 30 {
print("super")
} else {
Self.instance?.prt()
}
}
}
class foo1 : foo {
static var instance : foo? = nil
init() {
foo1.instance = self
}
func prt() {
print("foo1")
}
}
class foo2 : foo {
static var instance : foo? = nil
init() {
foo2.instance = self
}
func prt() {
print("foo2")
}
}
class foo3 : foo {
static var instance : foo? = nil
init() {
foo3.instance = self
}
}
var f1 : foo = foo1()
f1.prt()
var f2 : foo = foo2()
f2.prt()
var f3 : foo = foo3()
f3.prt()

- 615
- 5
- 16
I was trying to make a Weather
abstract class, but using protocols wasn't ideal since I had to write the same init
methods over and over again. Extending the protocol and writing an init
method had it's issues, especially since I was using NSObject
conforming to NSCoding
.
So I came up with this for the NSCoding
conformance:
required init?(coder aDecoder: NSCoder) {
guard type(of: self) != Weather.self else {
fatalError("<Weather> This is an abstract class. Use a subclass of `Weather`.")
}
// Initialize...
}
As for init
:
fileprivate init(param: Any...) {
// Initialize
}

- 3,407
- 2
- 27
- 33
Move all references to abstract properties and methods of Base class to protocol extension implementation, where Self constraint to Base class. You will gain access to all methods and properties of Base class. Additionally compiler check implementation of abstract methods and properties in protocol for derived classes
protocol Commom:class{
var tableView:UITableView {get};
func update();
}
class Base{
var total:Int = 0;
}
extension Common where Self:Base{
func update(){
total += 1;
tableView.reloadData();
}
}
class Derived:Base,Common{
var tableView:UITableView{
return owner.tableView;
}
}

- 562
- 6
- 16