首页 > 解决方案 > 泛型和约束(`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 子句,但这还不足以访问受约束的方法吗?:/

标签: swiftgenericscodabledecodablegeneric-constraints

解决方案


对我来说,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
    }
}

推荐阅读