Created
January 10, 2018 10:17
-
-
Save sgr-ksmt/fe10b14722ea15e9c55558b4afe7608c 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
protocol PushNotificationPayload: Decodable { | |
} | |
protocol SubscribeContainer { | |
func parse(_ json: Data) | |
} | |
extension SubscribeContainer { | |
func parse(_ json: Data) { | |
} | |
} | |
class Tsuchi { | |
static let shared = Tsuchi() | |
private init() {} | |
private struct Container<T: PushNotificationPayload>: SubscribeContainer { | |
let handler: (T) -> Void | |
func parse(_ data: Data) { | |
guard let payload = try? JSONDecoder().decode(T.self, from: data) else { | |
return | |
} | |
handler(payload) | |
} | |
} | |
private struct AnyContainer: SubscribeContainer { | |
let base: SubscribeContainer | |
} | |
private var container: AnyContainer? | |
func subscribe<T: PushNotificationPayload>(_ type: T.Type, handler: @escaping (T) -> Void) { | |
let container = Container<T>(handler: handler) | |
self.container = AnyContainer(base: container) | |
} | |
func received() { | |
guard let container = container else { | |
return | |
} | |
let json = ["name": "Taro"] | |
container.base.parse(try! JSONSerialization.data(withJSONObject: json, options: [])) | |
} | |
} | |
struct TestPayload: PushNotificationPayload { | |
let name: String | |
} | |
Tsuchi.shared.subscribe(TestPayload.self) { (payload) in | |
print("received: \(payload)") | |
} | |
Tsuchi.shared.received() // received: TestPayload(name: "Taro") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment