Created
September 20, 2017 13:31
-
-
Save KordianKL/3288163843fa2f5f02b72df74083aefd to your computer and use it in GitHub Desktop.
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
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) | |
default: | |
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