Codespree by Alexo

Введение в SwiftComposer

Motivation

Swift is very perfomant language with impressive Foundation API and great advatages for expressive functional programming. Most popular way to write code in functional paradigm is using method chaining and closures. However, sometime we would want to express our code in more declarative manner. Point free notation is most suitable approach for that.

Let’s look at example:

Code below represents repetitive pattern

requestPublisher
	.tryMap {
		let resp = try JsonDecoder().decode($0, as: ResponseDTO.self)
		return resp.toViewModel()
	}
	.mapError(...)
	.eraseToAnyPublisher()

Swift Composer offers to decouple closure code to two independent parts:

  • > decode data to struct
  • > mapping to viewModel

Compose both functions with functional fish operator

requestPublisher
	.tryMap(decode(as: ResponseDTO.self) >=> toViewModel)
	.mapError(...)
	.eraseToAnyPublisher()

Fish operator >=> composes functions and tell us that functions have side-effect like error throwing. (This operator has pure inplementation looks as >>>)

From that moment we have 2 seprate very reusable and composable high order functions: decode and toViewModel.

Expole the library

Swift Composer doesn’t push developer to write app with functional paradigm only. Main goal is having minimalistic tools to make code more declarative where it is necessary. Library exposes bunch of useful operators and functions to work with collections, primitives, structs, tuples and etc in point free manner.

Operators

Operator direction points to function application order.

<<< >>> - compose operator.

<=< >=> - compose operator with side effect

|> - pipe operator

<*> - pipe operator guaratees

<|> -

<?> -

Теги: