Can't use concrete subclass to implement a property in protocol in Swift

后端 未结 1 2003
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 13:50

I\'m doing something similar to the Bridge Pattern in JAVA, DriverType is a protocol requires a property named vehicle to be a Drivable

1条回答
  •  -上瘾入骨i
    2021-01-06 14:42

    I think the compiler error is misleading. DriverType states that any class adopting it must expose a vehicle property with Drivable type, not a property with a class type adopting the Drivable type.

    I would solve this issue by defining both the DriverType protocol and the Car class using generics:

    protocol Drivable {
        var speed: Double { get }
        init()
    }
    
    protocol DriverType {
        typealias T: Drivable
        var vehicle: T { get }
    }
    
    class Car: Drivable {
        var speed = 80.0;
        var brand = "BMW"
        required init() {}
    }
    
    class Driver: DriverType {   
        var vehicle: T = T() 
    }
    

    This explicitly states that classes adopting DriverType must expose a vehicle property whose type is any class adopting the Drivable protocol.

    0 讨论(0)
提交回复
热议问题