swagger-codegen icon indicating copy to clipboard operation
swagger-codegen copied to clipboard

[Swift 4] Property with type 'Any' does not conforms with codable protocol

Open vntguca opened this issue 7 years ago • 15 comments

Description

Current code generator for Swift 4 generates invalid code for JSON dictionaries or properties with object value type.

Property generated code:

open class TaskParameter: Codable {

    public var id: String?
    public var value: Any?

    public init() {}

}

Dictionary generated code:

open class EntityKey: Codable {
    public var entity: String?
    public var alias: String?
    public var fields: [String:Any]?

    public init() {}
} 
Swagger-codegen version

2.2.3

Swagger declaration file content or url
"definitions": {
"TaskParameter": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                },
                "value": {
                    "type": "object"
                }
            }
        },
"EntityKey": {
            "type": "object",
            "properties": {
                "entity": {
                    "type": "string"
                },
                "alias": {
                    "type": "string"
                },
                "fields": {
                    "type": "object",
                    "additionalProperties": {
                        "type": "object"
                    }
                }
            }
        }
}
Command line used for generation

swagger-codegen generate -i ./swagger.json -l swift4 -o ./api

Steps to reproduce

Generate the code with swagger-codegen 2.2.3 then try to compile the generated classes on Xcode 9 GM or any beta version.

Related issues/PRs
Suggest a fix/enhancement

Seems like this problem relies on the fact that Any is not (and will be not) Codable, thus a generic "AnyCodable" that conforms to this protocol should be used instead.

StackOverflow Discussion Apple Forum Discussion

vntguca avatar Sep 13 '17 03:09 vntguca

I've been having the same issue with swift3 and swift4 generated code, in XCode Version 9.1 (9B55). I now see that the code generated by editor.swagger.io is closer to correct, for swift4.

For this minimal example from OpenAPI I get three errors in the generated file CodableHelper.swift (this is about swift4).

line 19: decoder.dataDecodingStrategy = .base64Decode. Error: Type 'JSONDecoder.DataDecodingStrategy' has no member 'base64Decode' Solution: decoder.dataDecodingStrategy = .base64

line 39: encoder.dataEncodingStrategy = .base64Encode Error: Type 'JSONEncoder.DataEncodingStrategy' has no member 'base64Encode' Solution: encoder.dataEncodingStrategy = .base64

line 38: encoder.outputFormatting = (prettyPrint ? .prettyPrinted : .compact) Error: Type of expression is ambiguous without more context Solution: encoder.outputFormatting = .prettyPrinted [I don't know if this is what's intended here]

What is the status, is anybody working on this? Any estimate on when it will be fixed?

alexandrutomescu avatar Dec 05 '17 18:12 alexandrutomescu

In fact, my json is more complex than my above example, and I'm still getting errors such as: Type 'HttpResponse' does not conform to protocol 'Decodable'. This class has some members of custom types, for example: public var httpContext: HttpContext? Are these custom objects the problem?

Even for more basic classes I'm getting similar errors. For example, for

//
// KeyValuePairTypeObject.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//

import Foundation


open class KeyValuePairTypeObject: Codable {

    public var key: String?
    public var value: Any?

    public init() {}

}

I'm getting Type 'KeyValuePairTypeObject' does not conform to protocol 'Decodable' Type 'KeyValuePairTypeObject' does not conform to protocol 'Encodable'

Is it because of the member of type Any ?

What is the status, is anybody working on this? Any estimate on when it will be fixed?

Basically, at the moment we cannot get any running code at all, all code generated for swift3, swift4 and objective-c has strange errors such as these.

alexandrutomescu avatar Dec 05 '17 18:12 alexandrutomescu

@alexandrutomescu the same issue has occurred in the project I'm currently working on and I have been waiting for this to get fixed. It is because Any is a primitive type in Swift so it's not codable, which makes your whole class not codable.

A temporary workaround would be manually replace type Any with codable generics in your generated Swift code to get your project to run.

In your example, the original code:

open class KeyValuePairTypeObject: Codable {

    public var key: String?
    public var value: Any?

    public init() {}

}

could be changed to:

open class KeyValuePairTypeObject<T: Codable>: Codable {

    public var key: String?
    public var value: T?

    public init() {}

}

xiaochow avatar Dec 11 '17 18:12 xiaochow

Hey guys, We have a fix for this, will raise a PR.

danwoodel avatar May 28 '19 16:05 danwoodel

@danielwoodel just want to remind about this issue. Our team looking forward for solution =)

antonybrro avatar Jun 04 '19 22:06 antonybrro

Any update on this?

jmtaillant avatar Jun 25 '19 11:06 jmtaillant

Hey @jmtaillant, Yes sorry took some extra time because we wanted to test it vigiriously in our solution. It all looks good @wuf810 can we create a fork to your account and raise a PR. @wuf810 I think our branch contains a few fixes so we need 2 PRs. I think one was a date/time issue and this issue. They should not be related but I think they are in the same branch at the moment.

@jmtaillant Me and @wuf810 will let you know when we have created a PR Ill create a ticket in our jira board to factor it into a sprint.

danwoodel avatar Jun 26 '19 06:06 danwoodel

Any update on this maybe?

goors avatar Dec 30 '19 21:12 goors

Hi we have fixed this and we have been running on our own branch we return to work this week we will raise a pr next week if that weeks for you.

On 30 Dec 2019 21:10, Nikola [email protected] wrote:

Any update on this maybe?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://github.com/swagger-api/swagger-codegen/issues/6483?email_source=notifications&email_token=AMGC5BRZQSDWMPBLBBAMZDTQ3JPULA5CNFSM4D2WFPQ2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEH3GXPQ#issuecomment-569797566, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AMGC5BTBABBRO5VY3ERCVQ3Q3JPULANCNFSM4D2WFPQQ.

danwoodel avatar Jan 01 '20 12:01 danwoodel

Has the PR been raised yet? Any update on this?

ghost avatar Feb 10 '20 10:02 ghost

@sy-tech , no really. I'm not familiar with swift. But if you are willing to propose a PR, ping me and i can help you to get it merged.

HugoMario avatar Feb 10 '20 10:02 HugoMario

I actually dont know swift either, im just trying to build a client with it as an example. But i did some adjustments to my open api doc and it looks like this issue is gone.

Edit: The changes to swagger did not fix it. So i am still looking into it

ghost avatar Feb 10 '20 11:02 ghost

@danielwoodel any updates on this? This appears to still be an issue. Where can I find your branch with a solution?

cerupcat avatar Oct 16 '20 18:10 cerupcat

Until the changes to be released, you can resolve it by adding --type-mappings object=JSONValue as a workaround.

e.g.

swagger-codegen generate -i your-swagger.json -l swift5 -o output-dir --template-dir template-dir --template-engine handlebars --type-mappings object=JSONValue

alldne avatar Feb 07 '21 02:02 alldne

I'm still at this same problem, nothing work )

codegen line: swagger-codegen generate -i https://.... -l swift5 -o /Users/sergejudalov/Developer/alfabit-wallet-ios/alfawalletCustody --type-mappings object=JSONValue

public struct AdminWithdrawSymbolRequest: Codable {
    public var address: Any
    public var symbol: Any
    public var bchCode: Any?
    public var tag: Any?
    public var amount: Any
    public var otp: Any?

Can it be because of a bad Swagger file?

"AdminWithdrawSymbolRequest":{"properties":{"address":{"type":"string","title":"Address"},"symbol":{"type":"string","title":"Symbol"},"bch_code":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Bch Code"},"tag":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tag"},"amount":{"type":"string","title":"Amount"},"otp":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Otp"}},"type":"object","required":["address","symbol","amount"],"title":"AdminWithdrawSymbolRequest"}

Everything Any Screenshot 2024-03-25 at 13 45 47

2jumper3 avatar Mar 25 '24 12:03 2jumper3