Chris Mitchelmore
Chris Mitchelmore

Reputation: 6176

Swift protocol conformance with sub type

I would like to be able to implement a property of a protocol (B below) using a type that implements the requirements of the protocol. e.g. I want to get the code below to compile. At the moment, the error is "Type D does not conform to protocol B"

protocol A {
   func doSomething()
}

protocol B {
    var property: A { get }
}

class C: A {
    func doSomething() {
        //Stuff
    }
}

class D: B {
    var property: C = C()
}

Upvotes: 0

Views: 285

Answers (1)

Christian Dietrich
Christian Dietrich

Reputation: 11868

guess this should be done with associated types

protocol B {
    associatedtype T : A
    var property: T { get }
}

class D : B{
    var property : C = C()

}

Upvotes: 1

Related Questions