如何让Swift派生指定类型以解码JSON

问题描述

我发现自己经常使用try JSONDecoder().decode(Foo.self,from: Baz.foo.data),但我真的不喜欢它,因为就我而言,我知道Baz.foo.data始终可以投射到Foo上, Baz.bar.data-到Bar。我想通过定义要在Baz本身中解析后得到的类型来简化代码,以使其变为类似try JSONDecoder().decode(from: Baz.foo.data)或更好的形式-Baz.foo.decoded。我想到的代码如下:

struct Foo: Decodable {
    var foo: String
}

struct Bar: Decodable {
    var bar: String
}

enum Baz<T> where T: Decodable {
    case foo,bar
    
    var decoded: T {
        try! JSONDecoder().decode(self.type,from: self.data)
    }
    
    var type: T.Type {
        switch self {
        case .foo:
            return Foo.self as! T.Type
        case .bar:
            return Bar.self as! T.Type
        }
        
    }
    
    var data: Data {
        switch self {
        case .foo:
            return #"{"foo": "Foo string"}"#.data(using: .utf8)!
        case .bar:
            return #"{"bar": "Bar string"}"#.data(using: .utf8)!
        }
    }
}

但是要使用它,我仍然需要手动指定T,即:Baz<Foo>.foo.decoded。有没有办法让Swift自己指定它?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...