Swift 接受枚举的通用函数

Swift generic function accepting enums

我的情况好像很简单。我尝试编写漂亮的可重用代码来生成错误。

代码逻辑好像没问题。我们仅在运行时访问已初始化的属性。但是编译器抛出常见错误:

Instance member 'jsonValue' cannot be used on type 'T'

这是我的代码:

import Foundation

protocol ResponseProtocol {

    static var key: String { get }
    var jsonValue: [String : Any] { get }

}

struct SuccessResponse {

    let key = "success"

    enum EmailStatus: ResponseProtocol {

        case sent(String)

        static let key = "email"

        var jsonValue: [String : Any] { 
            switch self {
            case .sent(let email): return [EmailStatus.key : ["sent" : email]]
            }
        }
    }

    func generateResponse<T: ResponseProtocol>(_ response: T) -> [String : Any] {
        return [key : T.jsonValue]
    }

}

我真的希望这段代码能正常工作。因为现在我有这个的 "hardcode" 版本。

jsonValue 是方法参数的 属性 'response' 而不是 T

的 class 属性
protocol ResponseProtocol {

    static var key: String { get }
    var jsonValue: [String : Any] { get }

}

struct SuccessResponse {

    let key = "success"

    enum EmailStatus: ResponseProtocol {

        case sent(String)

        static let key = "email"

        var jsonValue: [String : Any] {
            switch self {
            case .sent(let email): return [EmailStatus.key : ["sent" : email]]
            }
        }
    }

    func generateResponse<T: ResponseProtocol>(_ response: T) -> [String : Any] {
        return [key : response.jsonValue]
    }

}

改用response.jsonValue。

func generateResponse<T: ResponseProtocol>(_ response: T) -> [String : Any] {
        return [key : response.jsonValue]
}