首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift 4 JSONDecoder解码协议类型

Swift 4 JSONDecoder解码协议类型
EN

Stack Overflow用户
提问于 2017-10-14 03:20:11
回答 2查看 3.8K关注 0票数 0

以下代码没有编译:

代码语言:javascript
复制
public protocol Foo: Decodable {
  var message: String { get }
}
struct Bar: Foo {
  let message: String
}

// the type conforming Foo protocol is passed from somewhere
let type: Foo.Type = Bar.self
decode(type: type, from: Data())

func decode<T>(type: T.Type, from data: Data) Where T: Decodable {
  let decoder = JSONDecoder()
  try! decoder.decode(type, from: data)
}

它抛出错误:Cannot invoke 'decode' with an argument list of type '(Foo.Type, from: Data)'

你们知道吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-10-14 04:45:12

你可以这样使用:

代码语言:javascript
复制
public protocol Foo: Decodable {
    var message: String { get }
}
struct Bar: Foo {
    let message: String
}

class ViewController: UIViewController {
    let bar = """
        {"message": "Sample message"}
    """

    override func viewDidLoad() {
        super.viewDidLoad()
        let type = Bar.self
        decode(type: type, from: bar.data(using: .utf8)!)
    }

    func decode<Foo>(type: Foo.Type, from data: Data) where Foo: Decodable {
        let decoder = JSONDecoder()
        let parsedData = try! decoder.decode(type, from: data)
        print(parsedData)
    }
}
票数 3
EN

Stack Overflow用户

发布于 2017-10-14 03:33:53

您应该在您的Bar上使用Bar来代替:

代码语言:javascript
复制
protocol Foo {
    var message: String { get }
}
struct Bar: Foo, Codable {
    let message: String
}

用法:

代码语言:javascript
复制
let bar = Bar(message: "Just a message")
if let data = try? JSONEncoder().encode(bar) {
    print(String(data:data, encoding:.utf8) ?? "") // {"message":"Just a message"}\n"// lets decode it
    if let decodedBar = try? JSONDecoder().decode(Bar.self, from: data) {
        print(decodedBar.message) //"Just a message\n"
     }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46740520

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档