Created
November 19, 2019 23:03
-
-
Save sstadelman/b45cdfb1788b529d2da42d16620676e4 to your computer and use it in GitHub Desktop.
Example of Codable enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum QuicklinkBinding: Codable { | |
case icon(String) | |
case title(String) | |
case description(String) | |
case action(Action) | |
enum CodingKeys: CodingKey { | |
case icon, title, description, action | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.container(keyedBy: CodingKeys.self) | |
switch self { | |
case .icon(let value): | |
try container.encode(value, forKey: .icon) | |
case .title(let value): | |
try container.encode(value, forKey: .title) | |
case .description(let value): | |
try container.encode(value, forKey: .description) | |
case .action(let value): | |
try container.encode(value, forKey: .action) | |
} | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
do { | |
if let value = try container.decodeIfPresent(String.self, forKey: .title) { | |
self = .title(value) | |
return | |
} else if let value = try container.decodeIfPresent(String.self, forKey: .description) { | |
self = .description(value) | |
return | |
} | |
let value = try container.decode(String.self, forKey: .icon) | |
self = .icon(value) | |
} catch { | |
let value = try container.decode(Action.self, forKey: .action) | |
self = .action(value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where
Action: Codable