enum PostType: Decodable { init(from decoder: Decoder) throws { // What do i put here? } case Image enum CodingKeys: String, CodingKey { case image } }
What do i put to complete this? Also, lets say i changed the case
to this:
case image(value: Int)
How do i make this conform to Decodable ?
EDit Here is my full code (which does not work)
let jsonData = """ { "count": 4 } """.data(using: .utf8)! do { let decoder = JSONDecoder() let response = try decoder.decode(PostType.self, from: jsonData) print(response) } catch { print(error) } } } enum PostType: Int, Codable { case count = 4 }
Final Edit Also, how will it handle an enum like this?
enum PostType: Decodable { case count(number: Int) }
We can make enum with raw values conform to the Codable protocol by just adopting it. 1 We can make enum with raw value support Codable by just adopting it. By declaring protocol conformance, Role becomes a codable type. 2 We can use it in a codable context without doing any extra work.
Understanding what Swift's Codable isWhen you only want to convert JSON data into a struct, you can conform your object to Decodable . If you only want to transform instances of your struct into Data , you can conform your object to Encodable , and if you want to do both you can conform to Codable .
In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.
It's pretty easy, just use String
or Int
raw values which are implicitly assigned.
enum PostType: Int, Codable { case image, blob }
image
is encoded to 0
and blob
to 1
Or
enum PostType: String, Codable { case image, blob }
image
is encoded to "image"
and blob
to "blob"
This is a simple example how to use it:
enum PostType : Int, Codable { case count = 4 } struct Post : Codable { var type : PostType } let jsonString = "{\"type\": 4}" let jsonData = Data(jsonString.utf8) do { let decoded = try JSONDecoder().decode(Post.self, from: jsonData) print("decoded:", decoded.type) } catch { print(error) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With