Swift:覆盖属性类

时间:2018-06-29 16:53:27

标签: swift generics swift4 swift-protocols

借助Swift协议,扩展和约束,我希望做两件事:

  1. 创建基本抽象类
  2. 子类和重写属性。

    class PropertyBase { }
    
    class PropA : PropertyBase {}
    
    class PropB : PropertyBase {}
    
    class ControllerBase {
        var prop: PropertyBase?
    }
    
    class ControllerA : ControllerBase{
        override var prop: PropA?
    }
    class ControllerB : ControllerBase{
        override var prop: PropB?
    }
    

错误:

  

无法覆盖类型为'PropertyBase的可变属性'prop'?协变类型为'PropA?

很高兴知道我如何用另一种方法实现这一目标?

编辑

我想为我要达到的目的更清楚地添加这个问题。

在该示例中,我正在构建一个处理未知对象类型的协议,我所知道的是该类型可以是StringInt或完全不同的类{{1} }。我想通过添加扩展来支持这些不同的类型类。至少那是我认为正确的方法,但是

Resource

我未知public protocol InstrumentProtocol : class { associatedtype Item: AnyObject var item: Item? { get set } var identifier: String? { get } } public class AbstractBase : InstrumentProtocol { public var item: AnyObject? public var identifier: String? public init(_ i : AnyObject) { item = i } public func about() { print(self.item) // Any Object } } //// This is what I want to achieve, but it doesn't work public extension InstrumentProtocol where Self.Item : Instrument { public func about() { print(self.item) //Should be of Instrument type } } public extension InstrumentProtocol where Self.Item : String { public func about() { print(self.item) //Should be of String type } } 属性类型。在这种情况下,将是最好的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

class PropertyBase { }
class PropA : PropertyBase {}
class PropB : PropertyBase {}

protocol ControllerBaseType {
  associatedtype T: PropertyBase    
  var prop : T? { get set }
}

class ControllerA : ControllerBaseType {
  var prop: PropA?
}
class ControllerB : ControllerBaseType {
  var prop: PropB?
}

ControllerBaseType是您想要的抽象对象,并且每个子类中都有prop的特定实现

编辑: 根据@Honey的评论,我通过从子类中删除类型别名来简化了代码

EDIT2: 如果您确实需要ControllerBase作为课程,可以这样:

class ControllerBase<T: PropertyBase> {
  var prop : T?
}

class PropertyBase { }
class PropA : PropertyBase {}
class PropB : PropertyBase {}

class ControllerA : ControllerBase<PropA> {}
class ControllerB : ControllerBase<PropB> {}
相关问题