Functional Programming

func fetchData(_ completionHandler: @escaping (Data) -> Void)

fetchData { data in  self.doSomething(with: data) }
fetchData { [weak self] data in   self?.doSomething(with: data) }
fetchData { [weak self] data in    guard let self = self else { return }    self.doSomething(with: data) 
}

since this includes a lot of boilerplate code. So how can be do better…

Functions can be stored in variables

var increment: (Int) -> Int = { $0 + 1 }

Functions can be passed as arguments

[1, 2, 3].map { $0 * $0 }

Functions can return functions

func buildIncrementor() -> (Int) -> Int { return { $0 + 1 } }

protocol Weakifiable: class { }

extension NSObject: Weakifiable { }

extension Weakifiable {func weakify(_ code: @escaping (Self) -> Void) -> () -> Void {    return { [weak self] in               guard let self = self else { return }               code(self)            }       }  }
func weakify<T>(_ code: @escaping (T, Self) -> Void) -> (T) -> Void {   return { [weak self] arg in     guard let self = self else { return }      code(arg, self)   }}
fetchData( weakify { data, strongSelf in  strongSelf.doSomething(with: data)})

so here weakify is a function which enhances the piece of code, so we can call weakify a “pseudo-keyword”.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Incorporating Your Interests (Into Software)

Hello World Meet RAW.

17 Best Project Management Software To Use In 2020

best-project-management-software-2020

Quicksort Algorithm in Python

How to host your backend code on Heroku

Scala Days Conference | Tapad in Switzerland 2019

30 days of JavaScript

rowspan in HTML

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chirag Kukreja

Chirag Kukreja

More from Medium

Improving Our iOS Alerts Implementation Using Factory Pattern

XCODE: Set up TDD environment with xcode’s 3 Hidden Features.

iOS testing — 4 crossroads technique — Part 1

Namespace an excuse to talk about global variables