My case seems to be very simple. I try to write beautiful reusable code for generating errors.
The code logic seems to be fine. We are accessing only to initialized properties in runtime. But the compiler throws common error :
Instance member 'jsonValue' cannot be used on type 'T'
That's my code:
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]
}
}
I do really want this code to work. 'cos now I have "hardcode" version of this one.
the jsonValue is property of your method parameter 'response' not class property of 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]
}
}