gpt4 book ai didi

ios - Swift 泛型函数接受枚举

转载 作者:行者123 更新时间:2023-11-28 12:11:05 25 4
gpt4 key购买 nike

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

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com