Swift 具有泛型类型约束的可观测的快速扩展
我试图给Observable添加一个扩展。 代码如下所示:Swift 具有泛型类型约束的可观测的快速扩展,swift,generics,observable,where-clause,rx-swift,Swift,Generics,Observable,Where Clause,Rx Swift,我试图给Observable添加一个扩展。 代码如下所示: extension Observable where Element == ApiResponse<ItemsContainer<T>>, T:Codable 问题 如果不指定泛型值的模型类型,则无法将扩展约束到包含泛型值的模型类型 您只能基于扩展签名上的associatedtypes约束协议,或基于泛型类型约束泛型。因此,T无法识别,因为没有任何协议或泛型声明它 解决方案 因此,记住我上面所说的,模型类型需
extension Observable where Element == ApiResponse<ItemsContainer<T>>, T:Codable
问题
如果不指定泛型值的模型类型,则无法将扩展约束到包含泛型值的模型类型
您只能基于扩展签名上的associatedtype
s约束协议,或基于泛型类型约束泛型。因此,T
无法识别,因为没有任何协议或泛型声明它
解决方案
因此,记住我上面所说的,模型类型需要在扩展上下文中完全定义但是等等,这不能满足我们的要求,我们希望它是通用的强>
那么我们不需要模型类型,我们需要协议
我们有两种模型类型(ApiResponse和ItemsContainer),我们需要知道泛型类型,因此我们需要为每种类型提供两个协议
蜂群反应
让我们创建一个名为ApiResponseProtocol
public protocol ApiResponseProtocol {
associatedtype Model
var data: Model? { get }
}
public struct ApiResponse<ApiModel>: ApiResponseProtocol {
public let data: ApiModel?
}
很酷,associatedtype模型
将充当对象上ApiModel
的通用值。让我们使ApiResponse
符合ApiResponseProtocol
public protocol ApiResponseProtocol {
associatedtype Model
var data: Model? { get }
}
public struct ApiResponse<ApiModel>: ApiResponseProtocol {
public let data: ApiModel?
}
扩大
现在,由于我们可以从协议中访问每个泛型类型(associatedtypes
),因此输出将如下所示:
// This would be for example ApiResponse<ItemsContainer<Model>> where Model is a Model Type conforming to Codable
extension Observable where Element: ApiResponseProtocol, Element.Model: ItemsContainerProtocol, Element.Model.Item: Codable {}
//这可能是例如ApiResponse,其中Model是符合Codable的模型类型
可观察的扩展,其中元素:ApiResponseProtocol,元素.Model:ItemsContainerProtocol,元素.Model.Item:Codable{}
我认为您需要制定一个协议来表示ApiResponse,但如果没有更多的上下文,我无法确定是否会发布一个答案。