Abstract class in Swift?

Is there any progress of swift-evolution of abstract class topic?

Here is My Workaround for it:

class C {
    var x: Int

    init(_ x: Int) {
        self.x = x
    }

    func concreteMethod() {}
}

protocol AbstractMethodRequirementsForC {
    func abstractMethod()
}

typealias AbstractC = C & AbstractMethodRequirementsForC

class ConcrectC: AbstractC { ... }

Thanks.

The question is what do abstract classes buy you in Swift that you don’t already have from protocols. Protocols can supply function implementation, and can require that only classes implement them.

So how important is declaring storage for properties?

The only thing that I have wanted sometimes is the ability to call super on a protocol override of a default implementation. Abstract classes do have that.

2 Likes

I’m also hoping for that. In C++, we can use SuperclassName::methodName to call the default implementation. But in Swift, protocol is not like superclass whose methods can be overridden. In fact, the following code is not allowed.

protocol P {
    func f()
}
extension P {
    func f() {}
}

class C: P {}

class D: C {
    // this `override` will cause a compilation error
    override func f() {}
}

But if you provide the implementation of f in C, it will be fine to override.

1 Like

Imagine such case where you have lots of properties to initialize in many classes/structs. if we have abstract class, the code may look like this:

abstract class C {
    let x: Int
    let y: Int
    let z: Int

    init(x: Int, y: Int, z: Int) {
        self.x = x
        self.y = y
        self.z = z
    }

   abstract func abstractMethod()
}

class D: C {
    let d: Int
    init(x: Int, y: Int, z: Int, d: Int) {
        self.d = d
        super.init(x: x, y: y, z: z)
    }

    override func abstractMethod() {}
}

class E: C {
    let e: Int
    init(x: Int, y: Int, z: Int, e: Int) {
        self.e = e
        super.init(x: x, y: y, z: z)
    }

    override func abstractMethod() {}
}

If I use protocol, is there any way to avoid the duplicate code of self.xxx = xxx?

Would synthesis of stored properties on conforming types be sufficient? i.e.:

protocol A {
    var x: Int { get set }
    var y: Int { get set }
    var z: Int { get set }
}

struct B: A { 
  /// var x, y, z: Int is auto-synthesized
}
Terms of Service

Privacy Policy

Cookie Policy