[英]Swift 5.1 generic usage in subclass
我有以下数据模型类来表示 MyDataModel:
public class MyDataModel <T> : Codable, Comparable where T:Codable {
...
}
接下来,我实现了一个包含 MyDataModel 实例的视图。 我显然无法在 UIView 的子类中保存通用参数,因此我尝试按如下方式解决它:
protocol MyDataProtocol {
associatedtype T:Codable
var dataParam:T { get set }
}
public class MyDataView: UIView {
public var myData:some MyDataProtocol?
}
但我收到一个错误
An 'opaque' type must specify only 'Any', 'AnyObject', protocols, and/or a base class
所以我可以使用 Any? 作为 MyDataProtocol 的类型,但这仍然不会告诉我 MyDataModel 的参数类型。 我想知道这里的解决方案是什么以及处理这个问题的正确方法。
您应该为 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.