首页 > 解决方案 > 将 JSON 编码器与 Codable 类型的计算变量一起使用

问题描述

凭借我的新手 swift 技能,我正在努力找出正确的 swift 语法来让这个游乐场工作。取决于我如何尝试解决它,我要么得到

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

这类似于这个问题中解决的问题 Using JSON Encoder to encoding a variable with Codable as type or I get

' (T) -> ()' 要求 'Encodable' 符合 'Encodable'

我真的很感激有解释的解决方案

编辑 为了提供更多上下文,我在这里尝试实现的模式是用于中间件路由器。根据应用程序中的操作,路由器将构建网络请求。codableParam 的目的是为用例提供一致的结构。因此,所有情况都将返回 nil 或 Codable 类型。

struct unityAuthenticationRequest: Codable {
    var username : String
    var password : String
}

enum test  {
    case volume
    case num2
    case num3

    var codableParam: Encodable? {
        switch self {
        case .volume:
            return unityAuthenticationRequest(username: "uname", password: "pwrods")
        default:
            return nil
        }
    }
}

func saveObject<T:Encodable>(_ object: T) {
    let data = try? JSONEncoder().encode(object)
}

func dx<T: Codable>(fx: T) {
    let datax = try? JSONEncoder().encode(fx)
}

let r = test.volume
saveObject(r.codableParam)

标签: swiftgenericscodableencodable

解决方案


错误消息几乎可以告诉您发生了什么:

Fatal error: Optional<Encodable> does not conform to Encodable
  because Encodable does not conform to itself.
  You must use a concrete type to encode or decode.:
    file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.74.1/src/swift/stdlib/public/core/Codable.swift, line 3960

然而,它很容易修复,只需像这样更改您的第一行:

var codableParam: unityAuthenticationRequest? {
    switch self {
    case .volume:
        return unityAuthenticationRequest(username: "uname", password: "pwrods")
    default:
        return nil
    }
}

现在,您的参数确实具有具体类型,并且通过最小的语法更改即可满足要求。

我仍然很难弄清楚这种类型的代码如何以最容易理解的方式传递你的意图,但我们必须更多地了解你的意图才能改进它。


推荐阅读