Skip to content
This repository was archived by the owner on Mar 29, 2018. It is now read-only.

ExSwift

pNre edited this page Jun 21, 2014 · 4 revisions

ExSwift

The following methods are defined as static on the class ExSwift.

#Methods

###after

  • after <P, T> (n: Int, call: (P...) -> T) -> ((P...) -> T?)
  • after <T> (n: Int, call: Void -> T) -> (Void -> T?)

Creates a wrapper that, executes function only after being called n times.

Example

let f = ExSwift.after(2, { println("Ciao") })
f()
// → 
f()
// → 
f()
// → Ciao
f()
// → Ciao

###once

  • once <P, T> (call: (P...) -> T) -> ((P...) -> T?)
  • once <T> (call: Void -> T) -> (Void -> T?)

Creates a wrapper that, when called for the first time (only) invokes function.

Example

let greet = ExSwift.once { (names: String...) -> () in println("Hello " + names[0]) }

greet("World")
// → Hello World

greet("People")
// → 

###partial

  • partial <P, T> (function: (P...) -> T, _ parameters: P...) -> ((P...) -> T)

Creates a wrapper that, when called, invokes function with any additional partial arguments prepended to those provided to the new function.

Example

let add = {
    (params: Int...) -> Int in
    return params.reduce(0, { return $0 + $1 })
}

let add5 = ExSwift.partial(add, 5)

add5(10)
// → 15

add5(1, 2)
// → 8

###bind

  • bind <P, T> (function: (P...) -> T, _ parameters: P...) -> (Void -> T)

Creates a wrapper (without any parameter) that, when called, invokes function automatically passing parameters as arguments.

Example

let concat = {
    (params: String...) -> String in
    return params.implode(" ")!
}

let helloWorld = ExSwift.bind(concat, "Hello", "World")

helloWorld()
// → Hello World

###cached

  • cached <P, R> (function: (P...) -> R, hash: ((P...) -> P)) -> ((P...) -> R)
  • cached <P, R> (function: (P...) -> R) -> ((P...) -> R)

Creates a wrapper for function that caches the result of function's invocations. hash, if specified, is the parameters based hashing function that computes the key used to store each result in the cache.

Example

// Slow Fibonacci
func fib(params: Int...) -> Int {
    let n = params[0]
    
    if n <= 1 {
        return n
    }
    return fib(n - 1) + fib(n - 2)
}

let fibonacci = Ex.cached(fib)

// This one is computed (fib is called 465 times)
fibonacci(12)

// The results is taken from the cache (fib is not called)
fibonacci(12)
Clone this wiki locally