Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hope to support inheritance #8

Closed
faimin opened this issue Mar 1, 2021 · 4 comments
Closed

hope to support inheritance #8

faimin opened this issue Mar 1, 2021 · 4 comments

Comments

@faimin
Copy link

faimin commented Mar 1, 2021

No description provided.

@dgrzeszczak
Copy link
Owner

Hey, do you have any issue I can replicate ?

@faimin
Copy link
Author

faimin commented Mar 2, 2021

yes, keyedCoable seem to don't support inheritance of class

demo code

class SuperClass {
    var name: String?
    var sex: String?
    var age: Int?
}

class SubClass: SuperClass, Codable {
    var a: String?
    var b: Int?
    
    enum CodingKeys: String, KeyedKey {
        case a, b
    }
}

private let jsonString = """
{
    "name": "John",
    "age": 18,
    "sex": "F",
    "a": "aa",
    "b": 100,
    "qqqq": {
        ".greeting": "Hallo world",
        "details": {
            "description": "Its nice here"
        }
    },
    "longitude": 3.2,
    "latitude": 3.4
}
"""

func testCodable() throws {
        let jsonData = jsonString.data(using: .utf8)!
        
        let model = try SubClass.keyed.fromJSON(jsonData)
        
        print(model) 
}

result

(CodableTests.SubClass) model = 0x00006000003a4180 {
  CodableTests.SuperClass = {
    name = nil
    sex = nil
    age = nil
  }
  a = "aa"
  b = 100
}

iShot2021-03-02 10.15.00.png

@dgrzeszczak
Copy link
Owner

dgrzeszczak commented Mar 2, 2021

Thank you for detailed description. I'll look on that but it may be hard to support - it's known issue of Codables and it's not related with KeyedCodables.

What do you think to use composition instead of inheritance? Using @Flat you will use the same JSON format. Your example will look like that.

class SuperClass: Codable {
    var name: String?
    var sex: String?
    var age: Int?
}

class SubClass: Codable {
    var a: String?
    var b: Int?

    @Flat var c: SuperClass // may be optional as well @Flat var c: SuperClass?
}

@faimin
Copy link
Author

faimin commented Mar 2, 2021

@dgrzeszczak amazing, It fulfills my needs, thanks.

@faimin faimin closed this as completed Mar 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants