Сетевые запросы с необязательным типом возврата с дженериками в SwiftIOS

Программируем под IOS
Ответить
Гость
 Сетевые запросы с необязательным типом возврата с дженериками в Swift

Сообщение Гость »


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         }     } } 
The

Код: Выделить всё

objectType
is what type of object is to be expected as a result of the request (used to decode the JSON received). For some events, this is some Decodable, for others nil (no data expected as return).

How 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

Код: Выделить всё

objectType
, or nothing at all (depending on the event)?[/b] Additionally, I need to convert from callback based function call to async/await syntax, because of the socketIO library (but this in itself works appart from the generics part).

I 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)             }         }     } 
But when calling like:

Код: Выделить всё

let User : User = try await ServerService.shared.sendWithAck(event: event, data: [updateData]) 
I get "Generic parameter 'T' could not be inferred" and "Cannot convert value of type 'T?' to specified type 'User'"


Источник: https://stackoverflow.com/questions/781 ... s-in-swift
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»