小编AnZ*_*AnZ的帖子

为什么不能使用协议`Encodable`作为func中的类型

我正在尝试通过符合Encodable协议的编码模型获取数据.但它无法encode像下面的代码那样调用func :

// MARK: - Demo2

class TestClass2: NSObject, Encodable {
    var x = 1
    var y = 2
}


var dataSource2: Encodable?

dataSource2 = TestClass2()

// error: `Cannot invoke 'encode' with an argument list of type '(Encodable)'`
let _ = try JSONEncoder().encode(dataSource2!)
//func encode<T>(_ value: T) throws -> Data where T : Encodable
Run Code Online (Sandbox Code Playgroud)

但在另一个演示中,它运作良好,为什么?

// MARK: - Demo1

protocol TestProtocol {
    func test()
}

class TestClass1: NSObject, TestProtocol {
    func test() {
        print("1")
    }

    var …
Run Code Online (Sandbox Code Playgroud)

protocols swift encodable

10
推荐指数
3
解决办法
3194
查看次数

标签 统计

encodable ×1

protocols ×1

swift ×1