Skip to content

Instantly share code, notes, and snippets.

import UIKit
// Type erasure example
protocol Joint {
associatedtype T
var count: T { get }
}
class SingleJoint: Joint {
@rdv0011
rdv0011 / swift-combine-multiple-publishers.md
Last active May 6, 2021 02:54
Swift Combine. Transform publisher output values and combine publishers together.

Quite often we encounter a problem of downloading files by links from the backend when writing apps. Let's take a look at how it might be achieved with Combine. The code below contains a dummy asymchronous task and transforms publisher's output values from a series of links to and an actual data items(images). A returned publisher might be used in a view model as a provider for UIImageView's for example.

import UIKit
import Combine
import WebKit
import PlaygroundSupport

enum CustomNetworkingError: Error {
    case invalidServerResponse
@rdv0011
rdv0011 / guard-statement.md
Last active December 29, 2019 12:27
Benefits of using a 'guard' statement in Swift language

It forces you to break ealier

  1. It has a positive test rather than negative one
  2. The else clause forces you to bring a program control outside the 'guard' scope (exit the function)
guard let var1 = par1 else { // else is mandatory
   return // must have. brings it outside the scope.
}

Unlike 'if' statement the variables declared at a condition block are visible in the whole 'guard' scope

@rdv0011
rdv0011 / swift-combine-retry.md
Last active September 5, 2022 09:25
Retry operation in Swift/Combine.

There is a function .retry() in Combine that helps to retry a request when something goes wrong with a long runing task. Although it is not enough just to call retry() to achieve retrying logic. The retry() function does not do another request but it re-subscribes only to a publisher. The below approaches might be used to solve the problem.

Using tryCatch

To make another request the tryCatch() might be used. In the code below if the first call fails there are three attempts to retry (retry(3)) that are made:

import UIKit
import Combine
import PlaygroundSupport

enum CustomNetworkingError: Error {
    case invalidServerResponse
@rdv0011
rdv0011 / encode-http-get-parameters.md
Last active December 9, 2019 14:00
A robust way to encode HTTP GET parameters

The code below demonstrates how to extend Encodable protocol to get parameters for the HTTP GET request directly out of the swift structure. Using this way there is no need to manually create an error prone dictionary of parameters. This code also shows one of the ways how to handle HTTP errors when making data task requests using URLSession dataTask publisher.

import UIKit
import Combine
import PlaygroundSupport

extension Encodable {
    var dictionary: [String: Any]? {
        guard let data = try? JSONEncoder().encode(self) else {
            return nil