我的情况似乎很简单。我尝试编写漂亮的可重用代码来生成错误。
代码逻辑似乎很好。我们只访问运行时的初始化属性。但编译器抛出了常见错误:
实例成员&#39; jsonValue&#39;不能用于类型&#39; <&#39;
那是我的代码:
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]
}
}
我确实希望此代码能够正常运行。现在,我有&#34;硬编码&#34;这个版本。
答案 0 :(得分:2)
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]
}
}
答案 1 :(得分:0)
改为使用response.jsonValue。
func generateResponse<T: ResponseProtocol>(_ response: T) -> [String : Any] {
return [key : response.jsonValue]
}