Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
extension Animoji: Codable {
func encode(to encoder: Encoder) throws {
try Animoji.Serialization(animoji: self).encode(to: encoder)
init(from decoder: Decoder) throws {
self = try Animoji.Serialization(from: decoder).animoji()
extension Animoji {
enum DeserializationError: Error {
case animojiEncodingError(String)
fileprivate struct Serialization: Codable {
private struct IphoneXData: Codable {
let emoji: String
let expression: Data
private var iPhoneX: IphoneXData?
private var notiPhoneX: String?
fileprivate init(animoji: Animoji) {
switch animoji {
case let .iPhoneX(emoji, expression):
self.iPhoneX = IphoneXData(emoji: emoji, expression: expression)
case let .notiPhoneX(emoji):
self.notiPhoneX = emoji
fileprivate func animoji() throws -> Animoji {
switch (iPhoneX, notiPhoneX) {
case let (.some(iPhoneXData), nil):
return Animoji.iPhoneX(iPhoneXData.emoji, iPhoneXData.expression)
case let (nil, .some(emoji)):
return Animoji.notiPhoneX(emoji)
throw DeserializationError.animojiEncodingError("Opps, can't decode \(self) to an Animoji type :(")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment