ios - Swift 泛型函数接受枚举

标签 ios swift generics generic-programming

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

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

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]
    }

}

我真的希望这段代码能够工作。因为现在我有了这个的“硬编码”版本。

最佳答案

jsonValue 是方法参数“response”的属性,不是 T 的类属性

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]
    }

}

关于ios - Swift 泛型函数接受枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48517886/

相关文章:

java - 如何将泛型 (T) 的 ArrayList 转换为直接数组?

ios - 如何使用 NSUserDefaults 保存和加载 UITextField?

iphone - 使用 Quartz 2D 绘图时的模糊效果

ios - 错误域=NSCocoaErrorDomain 代码=3840 "Invalid value around character 1."UserInfo={NSDebugDescription=字符 1 周围的值无效。swift 4

ios - CAFilter 仍然是私有(private) API 吗?

swift - 音频持续时间返回 0.0

iOS Swift 库 - 目标具有传递依赖性 Google Analytics

Java:子类化泛型类

ios - 无法将类型 'NSTaggedPointerString' 的值转换为 'NSDictionary'。 swift/火力基地

java - 有没有办法将 Java 集合与扩展类类型一起使用?