Created
April 10, 2019 10:35
-
-
Save makleso6/a64d78d2578642089720a8567b7d9661 to your computer and use it in GitHub Desktop.
RawHashableConvertible
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
import UIKit | |
protocol RawHashableConvertible: RawRepresentable, Hashable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { } | |
extension RawHashableConvertible where RawValue == String { | |
var description: String { | |
return rawValue | |
} | |
var debugDescription: String { | |
return description | |
} | |
var hashValue: Int { | |
return rawValue.hashValue | |
} | |
func hash(into hasher: inout Hasher) { | |
self.rawValue.hash(into: &hasher) | |
} | |
var customMirror: Mirror { | |
return rawValue.customMirror | |
} | |
} | |
protocol CustomSerialization { | |
associatedtype ObjectType | |
func process(_ object: ObjectType) throws -> Data | |
} | |
struct AnyHashableSerialization<C>: CustomSerialization where C: RawHashableConvertible { | |
func process(_ any: [C: Any]) throws -> Data { | |
let new = any.reduce([String: Any](), { (result, dict) -> [String: Any] in | |
var mutable = result | |
mutable[dict.key.description] = dict.value | |
return mutable | |
}) | |
return try JSONSerialization.data(withJSONObject: new, options: []) | |
} | |
} | |
struct Keys: RawHashableConvertible { | |
var rawValue: String | |
init(rawValue: String) { | |
self.rawValue = rawValue | |
} | |
} | |
extension Keys { | |
static var none: Keys { return .init(rawValue: "none") } | |
static var some: Keys { return .init(rawValue: "some") } | |
static var value: Keys { return .init(rawValue: "value") } | |
} | |
let dict: [Keys: String] = [.none: "Value1", | |
.some: "Value2", | |
.value: "Value3"] | |
do { | |
let data = try AnyHashableSerialization().process(dict) | |
print(data) | |
let string = String(data: data, encoding: .utf8) | |
print(string as Any) | |
} catch { | |
print(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment