Skip to content

Instantly share code, notes, and snippets.

View Edudjr's full-sized avatar
🏠
Working from home

Eduardo Domene Junior Edudjr

🏠
Working from home
  • Mercado Livre
  • Sao Paulo
View GitHub Profile
enum AsyncError: Error {
case finishedWithoutValue
}
extension AnyPublisher {
func async() async throws -> Output {
try await withCheckedThrowingContinuation { continuation in
var cancellable: AnyCancellable?
var finishedWithoutValue = true
cancellable = first()
struct API {
//...
func loadTodo() -> AnyPublisher<Todo, Error> {
//...
}
}
class Client1 {
// 1. Make function async
func loadTodo() async {
extension AnyPublisher {
func async() async throws -> Output {
try await withCheckedThrowingContinuation { continuation in
var cancellable: AnyCancellable?
cancellable = first()
.sink { result in
switch result {
case .finished:
break
struct API {
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
func loadTodo() async throws -> Todo {
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(Todo.self, from: data)
}
}
class Client1 {
class Client1 {
var cancellable: AnyCancellable?
let api = API()
func loadTodo() {
cancellable = api.loadTodo()
.sink(receiveCompletion: { result in
switch result {
case .finished:
print("finished")
struct API {
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
func loadTodo() -> AnyPublisher<Todo, Error> {
URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: Todo.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
}
@Edudjr
Edudjr / repository-pattern.swift
Created February 16, 2022 11:18
Repository Pattern in Swift using Type Erasure
// Repository.swift
import Foundation
protocol Repository {
associatedtype Model
func get(id: String, completion: @escaping (Result<Model, Error>) -> Void)
func save(_ item: Model, completion: @escaping (Result<Model, Error>) -> Void)
func remove(_ item: Model, completion: @escaping (Result<Model, Error>) -> Void)
}
struct MusicSheetPlotter<T: Prototype> where T.CloneType: UIView {
let quarterNote: T
func plot(in view: UIView) {
...
stack.addArrangedSubview(quarterNote.clone())
stack.addArrangedSubview(quarterNote.clone())
stack.addArrangedSubview(quarterNote.clone())
...
protocol Prototype {
associatedtype CloneType
func clone() -> CloneType
}
extension UILabel: Prototype {
...
// Don't forget to specialise the return type!
func clone() -> UILabel {
UILabel(self)
struct MusicSheetPloter {
let quarterNote: UIView & Prototype
...
}