我有一个类,它接受一个包含func transform()
的泛型参数Tclass CacheRepository<T> {}
。其中,如果T
符合Codable
协议,则需要调用另一个具有以下签名func transformCodable<U: Codable>(ofType: U.Type)
的函数。但我没有做到这一点。下面是我在测试中遇到的编译错误。
试验1:
func transform() {
if T.self is Codable.Type {
// Error: In argument type 'CacheRepository<T>.T.Type' (aka 'T.Type'), 'T' does not conform to expected type 'Decodable'
sharedStorage!.transformCodable(ofType: T.self)
}
}
试验2:
func transform() {
if T.self is Codable.Type {
//Cannot invoke 'transformCodable' with an argument list of type '(ofType: (Codable))'
//Expected an argument list of type '(ofType: U.Type)'
sharedStorage!.transformCodable(ofType: (T as! Codable).self)
}
}
试验3:我试图在T is Codable
的情况下扩展CacheRepository
类,但是当在init()函数中调用时,扩展transform
函数永远不会被调用。如果我在实例创建之后调用它,它并不是在所有情况下都会被调用。
class CacheRepository<T> {
func transform() {
print("non-codable transform")
}
}
extension CacheRepository where T: Codable {
func transform() {
sharedStorage!.transformCodable(ofType: T.self)
}
}
示例:这是可行的
let transform = CacheRepository<Int>().transform()
但是,如果我在CacheRepository
类中添加了一个共享实例,并试图在实例化后调用transform
,则不会调用它。真正奇怪的是,如果我在console中的新实例上调用tranform
,就会调用正确的transform
。
发布于 2019-05-18 05:25:50
这怎么回事?
extension CacheRepository where T: Codable {
func transform() {
print("Codable")
sharedStorage!.transformCodable(ofType: T.self)
}
}
extension CacheRepository {
func transform() {
print("Non-codable")
}
}
这在一个非常简单的CacheRepository
中就像预期的那样工作。但不确定它是否能在您的实际CacheRepository
中工作,请尝试。
https://stackoverflow.com/questions/56195840
复制相似问题