首页 > 解决方案 > swift 无法使用类型为“(对象:可编码)”的参数列表调用“xxx”

问题描述

Cannot invoke 'encodeTest' with an argument list of type '(object: Encodable)'当我使用下面的代码调用 test2 之类的函数时,出现错误。

这是代码:

//test func
func encodeTest<T>(object: T) where T: Encodable {
    // The object should be AnyObject which conforms to Encodable.
    let encoder = JSONEncoder()
    if let _ = try? encoder.encode(object) {
        print("encode success.")
        // I need fix the json here.
    }
}

class Test: Encodable {
    var a = "a"
    var b = "b"
}

//test1
var t: Test?
t = Test()
// it is ok.
encodeTest(object: t)


//test2
if let tf = t as Encodable? {
    // Cannot invoke 'encodeTest' with an argument list of type '(object: Encodable)'
    encodeTest(object: tf)
}

调用失败encodeTest(object: tf),如何解决?谢谢你的帮助!

标签: swift4

解决方案


推荐阅读