0

I have a parent class with several methods and attributes:

class Animal {
   var var1: ...
   var var2: ...

   func func1() {}
   func func2() {}
}

And Child class:

class Dog: Animal, Codable {
   var name = ""
}

I need to add to parent class a method, that will return result of JSONEncoder().encode for child class. Something like:

let dog = Dog()
dog.name = "Bob"
let jsonString = dog.jsonString() // {"name":"Bob"}

Can I do this?

Serhii Didanov
  • 2,200
  • 1
  • 16
  • 31

1 Answers1

1

Just create a String with the result of encode

extension Encodable {
    func jsonString() -> String {
        let data = try! JSONEncoder().encode(self)
        return String(data: data, encoding: .utf8)!
    }
}

let dog = Dog()
dog.name = "Bob"
dog.jsonString()

// {"name":"Bob"}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160