swift - 泛型和约束(`Instance method '...' 要求 'T' 符合 'Decodable'`)
问题描述
我有一个通用结构,允许使用不同的类型。我不想将整个结构限制为仅可解码项目。
修复以下错误的最佳方法是什么,我尝试仅在 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 子句,但这还不足以访问受约束的方法吗?:/
解决方案
对我来说,T 只需要符合Decodable
某些部分而不符合其他部分是没有意义的。我会将结构重写为
struct Something<T: Decodable> {
func item(from data: Data) -> T? {
try? JSONDecoder().decode(T.self, from: data)
}
func getter() -> T {
let value = ...
if let data = value as? Data
return item(from: data) ?? defaultvalue
}
return defaultvalue
}
}
推荐阅读
- javascript - 获取函数外变量的值
- c# - C#如何检查事件是否异步执行
- ruby-on-rails - 如何在 image_tag rails 中显示带有 falback url 的 webp 图像
- php - 如何将值向上移动到键,并删除键。数组操作
- javascript - 在 JS 中重命名对象键
- docker - 如何将 MySQL 数据库部署到 Docker?
- javascript - 如何在 quill js 2.0 中初始化表?
- logging - 数据库更改的日志文件在哪里?
- sql-server - T-SQL 从父表中删除记录时数据库发生冲突
- java - 如何使用描述符(protobuf,java)将字节数组解析为 GeneratedMessage?