【发布时间】:2020-07-03 08:48:31
【问题描述】:
我有一个允许使用不同类型的通用结构。我不想将整个结构限制为仅可解码项目。
修复以下错误的最佳方法是什么,我尝试仅在 T 符合 Decodable 时执行一些代码:
Instance method '...' requires that 'T' conform to 'Decodable'
struct Something<T> {
...
func item<T>(from data: Data) -> T? where T: Decodable {
try? JSONDecoder().decode(T.self, from: data)
}
func getter() -> T {
let value = ...
if let value = value as? T { return value } // something simple like string
if let data = value as? Data, T.self is Decodable { // something complex
return item(from: data) ?? defaultValue // error is thrown here
}
return defaultValue
}
}
如您所见,我正在检查是否符合 if 子句,但这还不足以访问受约束的方法吗? :/
【问题讨论】:
标签: swift generics codable decodable generic-constraints