Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an enum Decodable in swift 4?

Tags:

enums

swift

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) } 
like image 259
swift nub Avatar asked Jun 16 '17 04:06

swift nub


People also ask

How do you make an enum conform to Codable?

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.

What is the difference between Codable and Decodable in Swift?

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 .

Can enum inherit Swift?

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.


1 Answers

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) } 
like image 90
vadian Avatar answered Oct 04 '22 09:10

vadian