Post

Creando puentes 

Existen 2 conceptos que nos facilitan la transformación de funciones síncronas a funciones asíncronas y a integrar vistas de SwiftUI en proyectos con UIKit

El primero, las Continuations permiten crear un puente entre una código síncrono y código asíncrono, de closures hacia Async-await.

///Cambia func fetchJson con patrón Callback a AsyncAwait
private func getJSONAsync<JSON:Codable>(url: URL, type: JSON.Type) async throws -> JSON {
    try await withCheckedThrowingContinuation { continuation in
        fetchJson(url: url, type: type.self, session: session) { result in
            continuation.resume(with: result)
        }
    }
}

Disponible desde iOS 13

Por otro lado UIHostingConfiguration permite la integración de vistas hechas en SwiftUI a las aplicaciones existentes en UIKit

lazy var dataSource: UICollectionViewDiffableDataSource<Int,MarvelCellCharacter> = {
        UICollectionViewDiffableDataSource<Int,MarvelCellCharacter>(collectionView: collectionView) { [self] collectionView, indexPath, character in
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "marvelCharacterCell", for: indexPath)
            
            cell.contentConfiguration = UIHostingConfiguration {
                MarvelCharacterCellView(character: character)
            }
            return cell
        }
    }()

Disponible a partir de iOS16

El código completo está disponible en el repositorio: APIRest Demo en Github