jhurray/Ladybug

generic type with transformersByPropertyKey

Opened this issue · 6 comments

Jenus commented

`public protocol BaseResponse : JSONCodable {
var statusCode:Int{get}
var statusmessage:String?{get}
var success:Bool?{get}

}
public struct PrimitiveResponse : BaseResponse {
public var status : Int = 0
public var succeeded:Bool?
public var message:String?
public var data:T?

// public static let transformersByPropertyKey: [PropertyKey: JSONTransformer] = [
// "status" : "statusCode",
// "succeeded" : "success"
// ]
}`

!!! compiler comes out the error "Static stored properties not supported in generic types"
Btw, this editor ignored the key part [ "< T : JSONCodable >" ].

Why not just make it a computed property?

Why not just make it a computed property?

May I please ask you to elaborate? I am trying to tackle the same problem and I have just started with swift. I checked computer properties and generics in swift came up with this

struct BaseResponse<T:JSONCodable>: BaseResponseProtocol {
    
    var response: Bool
    var error: Error
    var debug: [String]
    var forceUpdate: Bool
    var maintenance: Bool
    var data: T {
        get {
            if let _ = T.self as? UserCreateResponse.Type {
                return UserCreateResponse.self as! T
            } else {
                return 0 as! T
            }
        }
    }
    
}

I was talking about making transformersByPropertyKey a computed property to prevent it from being stored

@jhurray I'm not sure if I follow can you please provide an example?

Jenus commented

@jhurray, Thanks, it works.
public static var transformersByPropertyKey: [PropertyKey: JSONTransformer] { get{
return [ "status" : "statusCode",
"succeeded" : "success"]
}
}

but it would be better using computed property format as an example in your document. Thanks again!

Jenus commented

@serjooo
struct BaseResponse<T:JSONCodable>: BaseResponseProtocol {
var response: Bool
var error: Error
var debug: [String]
var forceUpdate: Bool
var maintenance: Bool
var data: T
public static var transformersByPropertyKey: [PropertyKey: JSONTransformer] { get{
return [ ...
"data" : T.transformer]
}
}