Skip to content

Instantly share code, notes, and snippets.

@jemmons
Created April 18, 2018 20:07
Show Gist options
  • Save jemmons/4185f5da775f855a838c9b2ccad0af1c to your computer and use it in GitHub Desktop.
Save jemmons/4185f5da775f855a838c9b2ccad0af1c to your computer and use it in GitHub Desktop.
Simple Encoder
import Foundation
class BoolEncoder: SingleValueEncodingContainer {
var codingPath: [CodingKey]
private(set) var value: Bool?
init() {
codingPath = []
}
func encodeNil() throws {
value = nil
}
func encode(_ value: Bool) throws {
self.value = value
}
func encode(_ value: String) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: Double) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: Float) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: Int) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: Int8) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: Int16) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: Int32) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: Int64) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: UInt) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: UInt8) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: UInt16) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: UInt32) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode(_ value: UInt64) throws {
fatalError("\(type(of: self)) only supports bools.")
}
func encode<T>(_ value: T) throws where T : Encodable {
fatalError("\(type(of: self)) only supports bools.")
}
}
import Foundation
class SpanishEncoder: Encoder, CustomStringConvertible {
private var container: BoolEncoder
var description: String {
switch container.value {
case true?:
return "sí"
case false?:
return "no"
case nil:
return "no sé"
}
}
init() {
container = BoolEncoder()
codingPath = []
userInfo = [:]
}
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any]
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
fatalError("This only supports single values.")
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
fatalError("This only supports single values.")
}
func singleValueContainer() -> SingleValueEncodingContainer {
return container
}
}
import Foundation
let encoder = SpanishEncoder()
try! true.encode(to: encoder)
print(encoder) //> sí
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment