Swift:覆盖属性类

标签 swift generics swift4 swift-protocols

通过 Swift 协议(protocol)、扩展和约束,我希望做两件事:

  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?
    }
    

错误:

Cannot override mutable property 'prop' of type 'PropertyBase?' with covariant type 'PropA?

很高兴知道我如何通过不同的方法实现这一目标?

编辑

我想更清楚地补充这个问题,以说明我想要实现的目标。

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

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
    }
}

我不知道 item 属性类型。在这种情况下,这将是最好的方法吗?

最佳答案

你可以这样做:

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 评论,我通过从子类中删除类型别名来简化代码

编辑2: 如果您确实需要 ControllerBase 作为一个类,您可以这样做:

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

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

class ControllerA : ControllerBase<PropA> {}
class ControllerB : ControllerBase<PropB> {}

关于Swift:覆盖属性类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51106343/

相关文章:

ios - 用UIScrollView缩放时,无法正确滚动到下端

generics - 在 Swift 中扩展所有类型?

ios - 使用 api 响应(使用 Gloss)更新存储的用户模型,而无需逐行更新每个键

ios - JSON 解析错误 - 类型 'RecentTvListData' 没有下标成员

ios - 在 iphone 6 中从后台重新打开时应用程序崩溃

java - Java 中的通用映射

swift - 核心数据实体之间的关系如何设置?

ios - ViewController 中的多个 UICollectionViews |不会调用一个 CollectionViews 委托(delegate)方法

swift - 无法将 swift 泛型子类转换为泛型父类(super class)

java - 不兼容的边界错误: Java Predicate generics