简体   繁体   English

子类中的 Swift 5.1 泛型用法

[英]Swift 5.1 generic usage in subclass

I have the following data model class to represent a MyDataModel:我有以下数据模型类来表示 MyDataModel:

  public class MyDataModel <T> : Codable, Comparable where T:Codable {

   ...
  }

Next I implement a view that holds an instance of MyDataModel.接下来,我实现了一个包含 MyDataModel 实例的视图。 I can not obviously hold a generic parameter in the subclass of UIView so I try to workaround it as follows:我显然无法在 UIView 的子类中保存通用参数,因此我尝试按如下方式解决它:

 protocol MyDataProtocol {
    associatedtype T:Codable
     var dataParam:T { get set }
 }

  public class MyDataView: UIView {

      public var myData:some MyDataProtocol?

  }

But I get an error但我收到一个错误

  An 'opaque' type must specify only 'Any', 'AnyObject', protocols, and/or a base class

So I can use Any?所以我可以使用 Any? as type for MyDataProtocol but that will still not tell me the param type of MyDataModel.作为 MyDataProtocol 的类型,但这仍然不会告诉我 MyDataModel 的参数类型。 I am wondering what is the solution here and right way to handle this issue.我想知道这里的解决方案是什么以及处理这个问题的正确方法。

You should set an object for myData property and the error wouldn't show.您应该为 myData 属性设置一个对象,并且不会显示错误。

public class MyDataModel <T> : Codable, Comparable where T:Codable {
    
    public static func == (lhs: MyDataModel<T>, rhs: MyDataModel<T>) -> Bool {
        <#code#>
    }
    
    public static func < (lhs: MyDataModel<T>, rhs: MyDataModel<T>) -> Bool {
        <#code#>
    }
    
}


public protocol MyDataProtocol {
    associatedtype T
    var dataParam:T? { get set }
}

class MyData: MyDataProtocol {
    var dataParam: Codable?
    typealias T = Codable
    
    init() {}
}

public class MyDataView: UIView {
    public var myData: some MyDataProtocol = MyData()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM