forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallback.swift
More file actions
88 lines (71 loc) · 2.15 KB
/
Callback.swift
File metadata and controls
88 lines (71 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import Foundation
public protocol CallbackEvent {
associatedtype Info
var info: Info { get }
}
public struct CallbackEvents {
public struct UnTypedEvent: CallbackEvent {
public var info: String
public init(info: String) {
self.info = info
}
}
public var untyped: UnTypedEvent.Type { UnTypedEvent.self }
private init() {}
}
public struct CallbackManager {
struct Observer<Event: CallbackEvent> {
let handler: (Event.Info) -> Void
}
fileprivate var observers = [Any]()
public init() {}
public init(observers: (inout CallbackManager) -> Void) {
var manager = CallbackManager()
observers(&manager)
self = manager
}
public mutating func on<Event: CallbackEvent>(
_: Event.Type = Event.self,
_ handler: @escaping (Event.Info) -> Void
) {
observers.append(Observer<Event>(handler: handler))
}
public mutating func on<Event: CallbackEvent>(
_: KeyPath<CallbackEvents, Event.Type>,
_ handler: @escaping (Event.Info) -> Void
) {
observers.append(Observer<Event>(handler: handler))
}
public func send<Event: CallbackEvent>(_ event: Event) {
for case let observer as Observer<Event> in observers {
observer.handler(event.info)
}
}
func send<Event: CallbackEvent>(
_: KeyPath<CallbackEvents, Event.Type>,
_ info: Event.Info
) {
for case let observer as Observer<Event> in observers {
observer.handler(info)
}
}
public func send(_ string: String) {
for case let observer as Observer<CallbackEvents.UnTypedEvent> in observers {
observer.handler(string)
}
}
}
public extension [CallbackManager] {
func send<Event: CallbackEvent>(_ event: Event) {
for cb in self { cb.send(event) }
}
func send<Event: CallbackEvent>(
_ keyPath: KeyPath<CallbackEvents, Event.Type>,
_ info: Event.Info
) {
for cb in self { cb.send(keyPath, info) }
}
func send(_ event: String) {
for cb in self { cb.send(event) }
}
}