0

I need an extended property in subclass, but this code doesn't compile.

protocol A {
}
protocol B: A {
}
protocol C: A {
}

class Base {
    var presenter: A?
}
class Left: Base {
    override var presenter: B?
}
class Right: Base {
    override var presenter: C?
}

How to implement this on Swift 2?

adnako
  • 1,287
  • 2
  • 20
  • 30
  • 1
    this is not possible because you would change the contract for your superclass. This looks like an architecture problem that should be probably solved either by generics, associated types or better overall design. – Sulthan Sep 07 '16 at 12:58
  • I just do not want superclass knows about subclass details. Why this is an architecture problem? Now I cast this property in each subclass. – adnako Sep 07 '16 at 13:11
  • There are quite a few problems with what you're trying to do – [read-write properties are invariant](http://stackoverflow.com/a/37810234/2976878) & [protocols don't conform to themselves](http://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself). As Sulthan says, you're going to have to re-think your design. What's your actual use case? – Hamish Sep 07 '16 at 17:48

1 Answers1

0

You can't override or change property type in swift, but casting might help you. Check Left class in this code for example:

protocol A {
}
protocol B: A {
}
protocol C: A {
}

class Base {
    var presenter: A?
}


class Left: Base {

    init(persenter : B?) {
        self.presenter = presenter
    }

    func test() {
        print(presenter as! B)
    }
}

class Right: Base {
    var presenter: C?  //WON'T COMPILE
}
Mostafa Abdellateef
  • 1,145
  • 14
  • 12
  • Thanks, I made a new lazy property and cast presenter there. I want superclass doesn't know anything about subclassed details of this property. Is this a bad design or swift's feature? – adnako Sep 07 '16 at 13:13
  • It is not a bad design in my opinion, simply you can't change the variable type after declaration which makes sense in a typed language. And still super class doesn't know anything about subclass details except that it includes a property named presenter and it's conforming to protocol named A – Mostafa Abdellateef Sep 07 '16 at 13:28