jhurray / Ladybug

A powerful model framework for Swift 4
MIT License
147 stars 5 forks source link

generic type with transformersByPropertyKey #4

Open Jenus opened 7 years ago

Jenus commented 7 years ago

`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 >" ].

jhurray commented 7 years ago

Why not just make it a computed property?

serjooo commented 7 years ago

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

}
jhurray commented 7 years ago

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

serjooo commented 7 years ago

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

Jenus commented 7 years ago

@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 7 years ago

@serjooo struct BaseResponse: 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] } }