![](/img/trans.png)
[英]Swift generics & protocols: Return specialized type from static function?
[英]Swift Protocols with Associated Type and Generics calling wrong function
我试图让我的问题很简单。 我整天都在努力使它工作,但是没有运气。 我有两个协议。 可分解和可请求。
protocol Decodable { }
struct D: Decodable { }
protocol Requestable {
associatedtype Model
}
extension Requestable {
func returnValue() {
Utils.doSomething(Model)
}
}
和一类实用程序
class Utils {
static func doSomething<T>(param: T) {
print("Default")
}
static func doSomething<T: Decodable>(param: T) {
print("Decodable")
}
static func doSomething<T: Decodable>(param: [T]) {
print("Decodable Array")
}
}
我创建一个实现Requestable的结构R,并将类型别名Model赋予String
struct R: Requestable {
typealias Model = String
}
当我运行R()。returnValue()函数时,它将显示Default
。 不出所料。
我创建一个实现Requestable的结构R2,并将类型别名Model赋予正在实现Decodable的D
struct R2: Requestable {
typealias Model = D
}
当我运行R2()。returnValue()函数时,它将显示Default
。 但是我期望它会打印Decodable
因为Model D
符合Decodable
。
我创建一个实现Requestable的结构R3,并将类型别名Model赋予[D],其中数组元素正在实现Decodable
struct R3: Requestable {
typealias Model = [D]
}
当我运行R3()。returnValue()函数时,它将显示Default
。 但我期望它会打印Decodable Array
因为Model D
符合Decodable
。
任何帮助表示赞赏。
更新
在这种情况下,无法使用AnyRequestable并在运行时进行检查,因为在实际代码中,Generic是返回值,无法动态检查。
在实际的代码功能中,签名就像
public static func ResponseSerializer<M>() -> ResponseSerializer<M, NSError> {}
public static func ResponseSerializer<M: Decodable>() -> ResponseSerializer<M, NSError> {}
public static func ResponseSerializer<M: Decodable>() -> ResponseSerializer<[M], NSError> {}
这是预期的结果。 您忘记为Model
关联类型声明Decodable
一致性。 这应该解决它:
protocol Requestable {
associatedtype Model: Decodable
}
编辑:阅读您的评论,我现在了解您的问题。 问题是,您要的内容需要运行时,无法静态实现:
class Utils {
static func doSomething<T>(param: T) {
if let param = param as? Decodable {
print("Decodable")
} else {
print("Default")
}
}
}
考虑一下; 在编译代码时,在returnValue
范围内,编译器仅知道Model
是关联的类型,而没有其他东西。 您可以显式声明一致性Decodable
,或者编译器采用默认情况,即<T>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.