When making requests to a server, sometimes data is expected as a result (e.g. GET) and sometimes not (e.g. PUT). In my case, I have a websocket connection which is, amongst other things, used to tell the server things (no data returned), but also to request data (data returned).
I have defined an enum with the different kinds of requests (events) for the server:
Код: Выделить всё
public enum OutgoingEvent: String, Codable { case user case identification // ... more events var objectType: Codable.Type? { switch(self) { case .user: User.self // ... more cases default: nil } } } Код: Выделить всё
objectTypeHow do I write a function that I can call for all kinds of events, and get as a return either the kind of object specified by
Код: Выделить всё
objectTypeI have tried this:
Код: Выделить всё
func sendWithAck(event: OutgoingEvent, data: [[String : Any]], completion: @escaping (Result) -> ()) throws { // getting data from socket ... guard let resultType = event.objectType else { completion(.success(nil)) return } guard let decodedObject = try? self.decodeFromDict(object: result, type: resultType) as? T else { completion(.failure(ServerCommunicationError.invalidDataFromServer("Could not decode result data."))) return } completion(.success(decodedObject)) } func sendWithAck(event: OutgoingEvent, data: [[String : Any]]) async throws -> T? { return try await withCheckedThrowingContinuation { continuation in do { try sendWithAck(event: event, data: data) { (result: Result) in continuation.resume(with: result) } } catch(let error) { continuation.resume(throwing: error) } } } Код: Выделить всё
let User : User = try await ServerService.shared.sendWithAck(event: event, data: [updateData]) Источник: https://stackoverflow.com/questions/781 ... s-in-swift
Мобильная версия