Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

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

Aleksey Lobanov alobanov

🏠
Working from home
View GitHub Profile

Keybase proof

I hereby claim:

  • I am alobanov on github.
  • I am robotlegs (https://keybase.io/robotlegs) on keybase.
  • I have a public key ASAJw2lMrtfotr_AXq0swF_jKdscm_OxPh-1uwL0IwM9owo

To claim this, I am signing this object:

@alobanov
alobanov / DelayType.swift
Created August 8, 2018 08:23
Refresh auth token
enum DelayType {
case immediate()
case constant(time: Double)
case exponential(initial: Double, multiplier: Double, maxDelay: Double)
case custom(closure: (Int) -> Double)
}
extension DelayType {
func make(_ attempt: Int) -> Double {
switch self {
@alobanov
alobanov / Middleware.swift
Created November 14, 2017 15:09
Middleware example
class CheckNilMiddleware: Middleware {
override func check(value: MiddlewareItem) -> MiddlewareItem {
switch value {
case .value(let str):
if str == nil {
return .error("Значение равно nil")
}
default: break
}
@alobanov
alobanov / СompositeTableDatasource.swift
Last active November 8, 2017 08:51
Пример создания
// создаем корневой контейнер
self.datasource = BaseCompoundItem()
// создаем модели секции
let section1 = SectionCompoundItem(identifier: "Section1", header: "Вселенная MARVEL", footer: "Marvel Comics — американская компания, издающая комиксы, подразделение корпорации «Marvel Entertainment»")
let section2 = SectionCompoundItem(identifier: "Section2", header: "Вселенная DC", footer: "DC Comics — одно из крупнейших и наиболее популярных издательств комиксов, наравне с Marvel Comics")
// создаем модели ячеек
let cap = CellCompoundItem(identifier: "cell2", cellIdentifier: "CellID", title: "Captain America", subtitle: "Стивен Роджерс")
let batman = CellCompoundItem(identifier: "cell5", cellIdentifier: "CellID", title: "Batman", subtitle: "Брюс Вэйн")
@alobanov
alobanov / CellCompoundItem.swift
Last active November 3, 2017 14:15
Модель ячейки
// Сделаем нашей модели read only протокол, только с необходимыми полями
protocol CellCompoundItemProtocol {
var title: String? {get}
var subtitle: String? {get}
var cellIdentifier: String {get}
}
class CellCompoundItem: CompoundItemProtocol, CellCompoundItemProtocol {
private let decoratedComposite: CompoundItemProtocol
var title: String?
@alobanov
alobanov / SectionCompoundItem.swift
Last active November 8, 2017 07:35
Модель секции
// Сделаем нашей модели read only протокол, только с необходимыми полями
protocol SectionCompoundItemProtocol {
var header: String? {get}
var footer: String? {get}
}
class SectionCompoundItem: CompoundItemProtocol {
private let decoratedComposite: CompoundItemProtocol
// основные поля которые мы добавили с помощью декоратора
@alobanov
alobanov / BaseCompoundItem.swift
Last active November 3, 2017 13:51
Базовая модель которая реализует общий протокол CompoundItemProtocol
class BaseCompoundItem: CompoundItemProtocol {
var children: [CompoundItemProtocol] = []
let level: CompoundItemLevel
let identifier: String
var items: [CompoundItemProtocol] {
return children
}
// инициализация без параметров создает рутовый элемент структуры
@alobanov
alobanov / CompoundItemProtocol.swift
Last active November 3, 2017 13:51
Общий интерфейс компонентов. Composite
// уровень вложенности
enum CompoundItemLevel {
case root, section, item
}
protocol CompoundItemProtocol {
// уникальный идентификатор
var identifier: String {get}
// уровень на котором находится элемент
var level: CompoundItemLevel {get}
@alobanov
alobanov / ChainOfResponsibility.swift
Last active October 24, 2017 11:58
🐝 Цепочка обязанностей — это поведенческий паттерн, позволяющий передавать запрос по цепочке потенциальных обработчиков, пока один из них не обработает запрос.
//: Playground - noun: a place where people can play
import UIKit
enum ChainResult {
case error(NSError)
case success
}
class ValidationValue {
@alobanov
alobanov / factory.swift
Last active October 1, 2017 14:26
🏭 Фабричный метод — это порождающий паттерн проектирования, который определяет общий интерфейс для создания объектов в суперклассе, позволяя подклассам изменять тип создаваемых объектов.
//: Playground - noun: a place where people can play
import UIKit
// Models
struct UniverseType {
static let marvel = MarvelHero.self
static let dc = DCHero.self
}