Skip to content

Instantly share code, notes, and snippets.

View AndreyPanov's full-sized avatar
🤚

Andrei Panov AndreyPanov

🤚
View GitHub Profile
@AndreyPanov
AndreyPanov / NSDictionaryExtension.swift
Last active November 29, 2022 05:10
Convert objc NSDictionary to swift dictionary
extension NSDictionary {
var swiftDictionary: [String : AnyObject] {
var swiftDictionary: [String : AnyObject] = [:]
let keys = self.allKeys.flatMap { $0 as? String }
for key in keys {
let keyValue = self.value(forKey: key) as AnyObject
swiftDictionary[key] = keyValue
}
return swiftDictionary
@AndreyPanov
AndreyPanov / Debounce.swift
Created August 10, 2017 16:59
Debounce function for Swift 3
func debounce(_ action: @escaping () -> Void) {
let lastFireTime = DispatchTime.now()
let dispatchDelay = TimeInterval(0.3)
DispatchQueue.main.asyncAfter(deadline: .now() + dispatchDelay) {
let now = DispatchTime.now()
let when = lastFireTime + dispatchDelay
if now >= when {
action()
}
final class Repository: Chainable {
var before: (()->())?
private let dataProdider: DataProvider
init(dataProdider: DataProvider = .init()) {
self.dataProdider = dataProdider
}
func getItem(onSuccess: @escaping (Item)->(), onError: @escaping (Error)->()) {
//background async request
protocol Chainable: class {
var before: (()->())? { get set }
func before(_ callback: @escaping ()->()) -> Self
func invoke()
}
extension Chainable {
@discardableResult
func onViewLoaded() {
view?.showLoadingIndicator()
repository
.before({ [weak self] in self?.view?.hideLoadingIndicator() })
.getItem(
onSuccess: { [weak self] item in
print(item.description)
},
onError: { [weak self] error in
print(error.localizedDescription)
func onViewLoaded() {
view?.showLoadingIndicator()
repository.getItem(
onSuccess: { [weak self] item in
self?.view?.hideLoadingIndicator()
print(item.description)
},
onError: { [weak self] error in
self?.view?.hideLoadingIndicator()
print(error.localizedDescription)
final class Repository {
private let dataProdider: DataProvider
init(dataProdider: DataProvider = .init()) {
self.dataProdider = dataProdider
}
func getItem(onSuccess: @escaping (Item)->(), onError: @escaping (Error)->()) {
//background async request
dataProvider.request.items { [weak self] data, error in
if let item = ItemBuilder(with: data) {
func applyStyle() {
StyleBuilder()
.guide()
.forEach { setStyle(with: $0) }
}
private func setStyle(with guide: Guide) {
switch guide {
case .headerLabel(let closure),
.bodyLabel(let closure):
func perform<T>(with identifier: String, closure: (T) -> Void) {
Mirror(reflecting: self).children.forEach { property in
guard
property.label?.contain(identifier) == true,
let value = property.value as? T
else { return }
//run closure
closure(value)
}
}
func guide() -> [Guide] {
return [
.headerLabel(headerLabel),
.bodyLabel(bodyLabel),
.loginTextField(loginTextField)
]
}