Subclass extension for superclasses

Hello,

I want to extend a class B with code, but also want to make code available to it's superclass.

struct C<T> {
    
}

class A {
    
}

class B: A {
    
}
extension B where Self: A {
    func foo() -> C<Self> {
        fatalError()
    }
}

How would I do that?

So why don't you extend the superclass ?

Code as is will not compile.

Dn't you want to define B as Protocol B, instead of class ?

But then I cannot inherit from A!

I don't understand your point:

class A {
    var a: Int = 0
}
class B: A {
    var b: Int = 0
}

extension A {
    func show() {
        print("a", a)
    }
}

let someB = B()
print("someB", someB.a)
someB.a = 100
someB.show()

We get:

  • someB 0
  • a 100

So B does get A extension, isn't it ?

Subclass extension for superclasses
 
 
Q