Skip to content

Instantly share code, notes, and snippets.

@sstadelman
Created November 19, 2019 23:03
Show Gist options
  • Save sstadelman/b45cdfb1788b529d2da42d16620676e4 to your computer and use it in GitHub Desktop.
Save sstadelman/b45cdfb1788b529d2da42d16620676e4 to your computer and use it in GitHub Desktop.
Example of Codable enum
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)
}
}
}
@sstadelman
Copy link
Author

where Action: Codable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment