Skip to content

Commit ec86a19

Browse files
authored
Merge pull request socketio#1119 from vonox7/completion-handler-nil
Don’t create empty closures when we don’t need them
2 parents 9708019 + e0cbe59 commit ec86a19

10 files changed

+29
-56
lines changed

Source/SocketIO/Client/SocketIOClient.swift

Lines changed: 7 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -204,33 +204,15 @@ open class SocketIOClient : NSObject, SocketIOClientSpec {
204204
leaveNamespace()
205205
}
206206

207-
/// Send an event to the server, with optional data items.
208-
///
209-
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
210-
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
211-
///
212-
/// - parameter event: The event to send.
213-
/// - parameter items: The items to send with this event. May be left out.
214-
open func emit(_ event: String, _ items: SocketData...) {
215-
do {
216-
try emit(event, with: items.map({ try $0.socketRepresentation() }))
217-
} catch {
218-
DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)",
219-
type: logType)
220-
221-
handleClientEvent(.error, data: [event, items, error])
222-
}
223-
}
224-
225-
/// Send an event to the server, with optional data items and write completion handler.
207+
/// Send an event to the server, with optional data items and optional write completion handler.
226208
///
227209
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
228210
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
229211
///
230212
/// - parameter event: The event to send.
231213
/// - parameter items: The items to send with this event. May be left out.
232214
/// - parameter completion: Callback called on transport write completion.
233-
open func emit(_ event: String, _ items: SocketData..., completion: @escaping () -> ()) {
215+
open func emit(_ event: String, _ items: SocketData..., completion: (() -> ())? = nil) {
234216
do {
235217
try emit(event, with: items.map({ try $0.socketRepresentation() }), completion: completion)
236218
} catch {
@@ -256,7 +238,7 @@ open class SocketIOClient : NSObject, SocketIOClientSpec {
256238
/// - parameter items: The items to send with this event. Send an empty array to send no data.
257239
/// - parameter completion: Callback called on transport write completion.
258240
@objc
259-
open func emit(_ event: String, with items: [Any], completion: @escaping () -> ()) {
241+
open func emit(_ event: String, with items: [Any], completion: (() -> ())? = nil) {
260242
emit([event] + items, completion: completion)
261243
}
262244

@@ -317,18 +299,18 @@ open class SocketIOClient : NSObject, SocketIOClientSpec {
317299
ack: Int? = nil,
318300
binary: Bool = true,
319301
isAck: Bool = false,
320-
completion: @escaping () -> () = {}
302+
completion: (() -> ())? = nil
321303
) {
322304
// wrap the completion handler so it always runs async via handlerQueue
323-
let wrappedCompletion = {[weak self] in
305+
let wrappedCompletion: (() -> ())? = (completion == nil) ? nil : {[weak self] in
324306
guard let this = self else { return }
325307
this.manager?.handleQueue.async {
326-
completion()
308+
completion!()
327309
}
328310
}
329311

330312
guard status == .connected else {
331-
wrappedCompletion()
313+
wrappedCompletion?()
332314
handleClientEvent(.error, data: ["Tried emitting when not connected"])
333315
return
334316
}

Source/SocketIO/Client/SocketIOClientSpec.swift

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -92,24 +92,15 @@ public protocol SocketIOClientSpec : AnyObject {
9292
/// Disconnects the socket.
9393
func disconnect()
9494

95-
/// Send an event to the server, with optional data items.
96-
///
97-
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
98-
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
99-
///
100-
/// - parameter event: The event to send.
101-
/// - parameter items: The items to send with this event. May be left out.
102-
func emit(_ event: String, _ items: SocketData...)
103-
104-
/// Send an event to the server, with optional data items and write completion handler.
95+
/// Send an event to the server, with optional data items and optional write completion handler.
10596
///
10697
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
10798
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
10899
///
109100
/// - parameter event: The event to send.
110101
/// - parameter items: The items to send with this event. May be left out.
111102
/// - parameter completion: Callback called on transport write completion.
112-
func emit(_ event: String, _ items: SocketData..., completion: @escaping () -> ())
103+
func emit(_ event: String, _ items: SocketData..., completion: (() -> ())?)
113104

114105
/// Call when you wish to tell the server that you've received the event for `ack`.
115106
///

Source/SocketIO/Engine/SocketEngine.swift

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
346346
if polling {
347347
disconnectPolling(reason: reason)
348348
} else {
349-
sendWebSocketMessage("", withType: .close, withData: [], completion: {})
349+
sendWebSocketMessage("", withType: .close, withData: [], completion: nil)
350350
closeOutEngine(reason: reason)
351351
}
352352
}
@@ -372,7 +372,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
372372

373373
DefaultSocketLogger.Logger.log("Switching to WebSockets", type: SocketEngine.logType)
374374

375-
sendWebSocketMessage("", withType: .upgrade, withData: [], completion: {})
375+
sendWebSocketMessage("", withType: .upgrade, withData: [], completion: nil)
376376
polling = false
377377
fastUpgrade = false
378378
probing = false
@@ -390,7 +390,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
390390
DefaultSocketLogger.Logger.log("Flushing probe wait", type: SocketEngine.logType)
391391

392392
for waiter in probeWait {
393-
write(waiter.msg, withType: waiter.type, withData: waiter.data, completion:waiter.completion)
393+
write(waiter.msg, withType: waiter.type, withData: waiter.data, completion: waiter.completion)
394394
}
395395

396396
probeWait.removeAll(keepingCapacity: false)
@@ -550,7 +550,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
550550
}
551551

552552
pongsMissed += 1
553-
write("", withType: .ping, withData: [], completion: {})
553+
write("", withType: .ping, withData: [], completion: nil)
554554

555555
engineQueue.asyncAfter(deadline: .now() + .milliseconds(pingInterval)) {[weak self, id = self.sid] in
556556
// Make sure not to ping old connections
@@ -606,7 +606,7 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
606606
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: SocketEngine.logType)
607607

608608
fastUpgrade = true
609-
sendPollMessage("", withType: .noop, withData: [], completion: {})
609+
sendPollMessage("", withType: .noop, withData: [], completion: nil)
610610
// After this point, we should not send anymore polling messages
611611
}
612612
}
@@ -617,10 +617,10 @@ open class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, So
617617
/// - parameter type: The type of this message.
618618
/// - parameter data: Any data that this message has.
619619
/// - parameter completion: Callback called on transport write completion.
620-
open func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data], completion: @escaping () -> ()) {
620+
open func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data], completion: (() -> ())? = nil) {
621621
engineQueue.async {
622622
guard self.connected else {
623-
completion()
623+
completion?()
624624
return
625625
}
626626
guard !self.probing else {

Source/SocketIO/Engine/SocketEnginePollable.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public protocol SocketEnginePollable : SocketEngineSpec {
6565
/// - parameter message: The message to send.
6666
/// - parameter withType: The type of message to send.
6767
/// - parameter withData: The data associated with this message.
68-
func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data], completion: @escaping () -> ())
68+
func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data], completion: (() -> ())?)
6969

7070
/// Call to stop polling and invalidate the URLSession.
7171
func stopPolling()
@@ -75,7 +75,7 @@ public protocol SocketEnginePollable : SocketEngineSpec {
7575
extension SocketEnginePollable {
7676
func createRequestForPostWithPostWait() -> URLRequest {
7777
defer {
78-
for packet in postWait { packet.completion() }
78+
for packet in postWait { packet.completion?() }
7979
postWait.removeAll(keepingCapacity: true)
8080
}
8181

@@ -219,7 +219,7 @@ extension SocketEnginePollable {
219219
/// - parameter withType: The type of message to send.
220220
/// - parameter withData: The data associated with this message.
221221
/// - parameter completion: Callback called on transport write completion.
222-
public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data], completion: @escaping () -> ()) {
222+
public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data], completion: (() -> ())? = nil) {
223223
DefaultSocketLogger.Logger.log("Sending poll: \(message) as type: \(type.rawValue)", type: "SocketEnginePolling")
224224

225225
postWait.append((String(type.rawValue) + message, completion))

Source/SocketIO/Engine/SocketEngineSpec.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ import Starscream
138138
/// - parameter type: The type of this message.
139139
/// - parameter data: Any data that this message has.
140140
/// - parameter completion: Callback called on transport write completion.
141-
func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data], completion: @escaping () -> ())
141+
func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data], completion: (() -> ())?)
142142
}
143143

144144
extension SocketEngineSpec {
@@ -180,7 +180,7 @@ extension SocketEngineSpec {
180180
}
181181

182182
/// Send an engine message (4)
183-
func send(_ msg: String, withData datas: [Data], completion: @escaping () -> () = {}) {
183+
func send(_ msg: String, withData datas: [Data], completion: (() -> ())? = nil) {
184184
write(msg, withType: .message, withData: datas, completion: completion)
185185
}
186186
}

Source/SocketIO/Engine/SocketEngineWebsocket.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,14 @@ public protocol SocketEngineWebsocket : SocketEngineSpec {
4141
func sendWebSocketMessage(_ str: String,
4242
withType type: SocketEnginePacketType,
4343
withData datas: [Data],
44-
completion: @escaping () -> ())
44+
completion: (() -> ())?)
4545
}
4646

4747
// WebSocket methods
4848
extension SocketEngineWebsocket {
4949
func probeWebSocket() {
5050
if ws?.isConnected ?? false {
51-
sendWebSocketMessage("probe", withType: .ping, withData: [], completion: {})
51+
sendWebSocketMessage("probe", withType: .ping, withData: [], completion: nil)
5252
}
5353
}
5454

@@ -63,7 +63,7 @@ extension SocketEngineWebsocket {
6363
public func sendWebSocketMessage(_ str: String,
6464
withType type: SocketEnginePacketType,
6565
withData datas: [Data],
66-
completion: @escaping () -> ()
66+
completion: (() -> ())?
6767
) {
6868
DefaultSocketLogger.Logger.log("Sending ws: \(str) as type: \(type.rawValue)", type: "SocketEngineWebSocket")
6969

Source/SocketIO/Manager/SocketManager.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,7 @@ open class SocketManager : NSObject, SocketManagerSpec, SocketParsable, SocketDa
286286
/// - parameter items: The data to send with this event.
287287
open func emitAll(_ event: String, withItems items: [Any]) {
288288
forAll {socket in
289-
socket.emit(event, with: items, completion: {})
289+
socket.emit(event, with: items, completion: nil)
290290
}
291291
}
292292

Source/SocketIO/Util/SocketTypes.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,10 @@ public typealias AckCallback = ([Any]) -> ()
7474
public typealias NormalCallback = ([Any], SocketAckEmitter) -> ()
7575

7676
/// A typealias for a queued POST
77-
public typealias Post = (msg: String, completion: (() -> ()))
77+
public typealias Post = (msg: String, completion: (() -> ())?)
7878

7979
typealias JSON = [String: Any]
80-
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [Data], completion: (() -> ()))
80+
typealias Probe = (msg: String, type: SocketEnginePacketType, data: [Data], completion: (() -> ())?)
8181
typealias ProbeWaitQueue = [Probe]
8282

8383
enum Either<E, V> {

Tests/TestSocketIO/SocketMangerTest.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ public class TestSocket : SocketIOClient {
198198
super.didDisconnect(reason: reason)
199199
}
200200

201-
public override func emit(_ event: String, with items: [Any], completion: @escaping () -> ()) {
201+
public override func emit(_ event: String, with items: [Any], completion: (() -> ())?) {
202202
expectations[ManagerExpectation.emitAllEventCalled]?.fulfill()
203203
expectations[ManagerExpectation.emitAllEventCalled] = nil
204204

Tests/TestSocketIO/SocketSideEffectTest.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,5 +511,5 @@ class TestEngine : SocketEngineSpec {
511511
func flushWaitingForPostToWebSocket() { }
512512
func parseEngineData(_ data: Data) { }
513513
func parseEngineMessage(_ message: String) { }
514-
func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data], completion: @escaping () -> ()) { }
514+
func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data], completion: (() -> ())?) { }
515515
}

0 commit comments

Comments
 (0)