如何用Codable类型定义变量?

Ram*_*mis 4 json swift swift-protocols swift4

我想用Codable类型创建变量.然后在JSONEncoder类中使用它.我认为下面的代码应该可以正常工作,但它给了我错误:

无法encode使用类型的参数列表调用(Codable).

如何声明JSONEncoder将无错的可编码变量?

struct Me: Codable {
    let id: Int
    let name: String
}

var codable: Codable? // It must be generic type, but not Me.

codable = Me(id: 1, name: "Kobra")

let data = try? JSONEncoder().encode(codable!)
Run Code Online (Sandbox Code Playgroud)

以下是如何使用函数传递Codable的类似问题.但我正在寻找如何使用变量(类变量)设置Codable.

Dee*_*pak 6

你的代码没问题,我们唯一需要关注的是Codable.

Codable是一个typealias不会给你泛型的.

JSONEncoder().encode(Generic confirming to Encodable).

所以,我修改了下面的代码,它可能会帮助你..

protocol Codability: Codable {}

extension Codability {
    typealias T = Self
    func encode() -> Data? {
        return try? JSONEncoder().encode(self)
    }

    static func decode(data: Data) -> T? {
        return try? JSONDecoder().decode(T.self, from: data)
    }
}

struct Me: Codability
{
    let id: Int
    let name: String
}

struct You: Codability
{
    let id: Int
    let name: String
}

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        var codable: Codability
        codable = Me(id: 1, name: "Kobra")
        let data1 = codable.encode()

    codable = You(id: 2, name: "Kobra")
    let data2 = codable.encode()
}
}
Run Code Online (Sandbox Code Playgroud)


PGD*_*Dev 5

我创建了与您相同的场景:

struct Me: Codable
{
    let id: Int
    let name: String
}

struct You: Codable
{
    let id: Int
    let name: String
}

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        var codable: Codable?

        codable = Me(id: 1, name: "Kobra")
        let data1 = try? JSONEncoder().encode(codable)

        codable = You(id: 2, name: "Kobra")
        let data2 = try? JSONEncoder().encode(codable)
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码没有给我任何错误。我唯一改变的是:

let data = try? JSONEncoder().encode(codable!)
Run Code Online (Sandbox Code Playgroud)

我没有打开包装codable,它工作正常。

  • 那就解释了。您需要使用具体类型。 (4认同)