Skip to content

glebfann/FunctionalPrimitives

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FunctionalPrimitives

Swift functional primitives.

Installation

Xcode

  1. Click File > Add Package Dependencies
  2. Paste the following link into the search field on the upper-right:
    https://github.com/gleb032/FunctionalPrimitives.git
    

Swift Package Manager

In Package.swift:

dependencies: [
    .package(url: "https://github.com/gleb032/FunctionalPrimitives.git", from: "1.0.2")
]

Examples

Converts a class method to a closure with a weak reference to the instance of the class.

For example we have ViewController:

class ViewController: UIViewController {
  let networkManager = NetworkManager()
  ...

  override func viewDidLoad() {
    super.viewDidLoad()
    networkManager.fetchData {
      self.updateUI()
    }
  }

  func updateUI() {
    ...
  }

}

This may causes a memory leak. Insted it we can use weakify:

  networkManager.fetchData(completion: weakify(self, in: ViewController.updateUI))

Actually this is semantically the same as:

networkManager.fetchData { [weak self] in
  self?.updateUI()
}

Partially apply function.

For example:

func sum(_ lhs: Int, _ rhs: Int) -> Int {
  lhs + rhs
}

let add3 = papply(sum, 3)
let result = add3(4) // result = 7

Curries/Uncurries a function with arguments.

For example:

func sum(_ lhs: Int, _ rhs: Int) -> Int {
  lhs + rhs
}

let curriedSum = curry(sum)
print(curriedSum(2)(3)) // 5

let uncurriedSum = uncurry(curriedSum)
print(uncurriedSum(2, 3)) // 5

Composes functions, i.e. composition of functions (A) -> (B) and (B) -> (C) will give (A) -> (C).

For example:

func double(_ num: Int) -> Int {
  return num * 2
}

func add5(_ num: Int) -> Int {
  return num + 5
}

func toString(_ num: Int) -> String {
  return String(num)
}

let pipeline = compose(double, add5, toString)
let result = pipeline(10) //  result = "25"

License

The project is released under the MIT License