Ladybug icon indicating copy to clipboard operation
Ladybug copied to clipboard

generic type with transformersByPropertyKey

Open Jenus opened this issue 8 years ago • 6 comments

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

} public struct PrimitiveResponse<T : JSONCodable> : 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 >" ].

Jenus avatar Oct 20 '17 08:10 Jenus

Why not just make it a computed property?

jhurray avatar Oct 20 '17 17:10 jhurray

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

serjooo avatar Oct 21 '17 17:10 serjooo

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

jhurray avatar Oct 21 '17 20:10 jhurray

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

serjooo avatar Oct 21 '17 21:10 serjooo

@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 avatar Oct 23 '17 02:10 Jenus

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

Jenus avatar Oct 23 '17 10:10 Jenus