使用JSONEncoder以Codable作为类型对变量进行编码 [英] Using JSONEncoder to encode a variable with Codable as type

查看:635
本文介绍了使用JSONEncoder以Codable作为类型对变量进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法让JSON和plist编码和解码都能正常工作,但只能直接调用特定对象上的编码/解码函数。

I managed to get both JSON and plist encoding and decoding working, but only by directly calling the encode/decode function on a specific object.

例如:

struct Test: Codable {
    var someString: String?
}

let testItem = Test()
testItem.someString = "abc"

let result = try JSONEncoder().encode(testItem)

这很有效且无问题。

但是,我试图获得一个只接受 Codable 协议一致性的函数作为类型并保存该对象。

However, I am trying to get a function that takes in only the Codable protocol conformance as type and saves that object.

func saveObject(_ object: Encodable, at location: String) {
    // Some code

    let data = try JSONEncoder().encode(object)

    // Some more code
}

这会导致以下错误:


无法使用类型为'(可编码)'的参数列表调用'encode'

Cannot invoke 'encode' with an argument list of type '(Encodable)'

查看编码函数的定义,好像它应该能够接受 Encodable ,除非 Value 是一些我不知道的奇怪类型。

Looking at the definition of the encode function, it seems as if it should be able to accept Encodable, unless Value is some strange type I don't know of.

open func encode<Value>(_ value: Value) throws -> Data where Value : Encodable


推荐答案

使用约束的泛型类型 Encodable

func saveObject<T : Encodable>(_ object: T, at location: String) {
    //Some code

    let data = try JSONEncoder().encode(object)

    //Some more code
}

这篇关于使用JSONEncoder以Codable作为类型对变量进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆