CocoaPods trunk is moving to be read-only. Read more on the blog, there are 19 months to go.

AnyFunction 1.0.4

AnyFunction 1.0.4

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Aug 2017
SwiftSwift Version 3.0
SPMSupports SPM

Maintained by Damouse.



  • By
  • Mickey Barboi

AnyFunction

Generic closures in Swift 1.3 that allow invocation of arbitrary functions through reflection.

This project is published on CocoaPods, but is suspended indefinitely. It was written before Swift 2 came out, and so likely doesn’t work anymore.

Functionality

Swift doesn’t allow for generic closures. Specifically, it doesn’t allow for variadic generic closures.

In other words, you can take a closure that has a generic signature:

func takesAClosure<A, B, C>((A, B) -> C) 

But you cant take closures that may have more or less parameters:

func takesAClosure<A, B, C>(passedClosure: (A, B) -> C) 

# This has to be a different function
func takesAClosure<A, C>(passedClosure: (A) -> C) 

The point of this library is create a type that can standin for any closure with any number of parameters. This is a useful function if you want to make a library that can accept arbitrary closures and both resolve and invoke them dynamically.

func TakesAnyFunction<A: AnyFunction>(A)

TakesAnyFunction((a: Int, b: String) in 1 })
TakesAnyFunction((c: Bool) in "1" })

It works by reflecting the type of the passed closure, wrapping it in an abstract Closure class, then exposing a method call that takes an array of arguments. If the number and type of arguments match the signature of the passed closure then the original closure is invoked and the results returned.

Example

import AnyFunction

let c = Closure.wrap { (a: String) in a }
let ret = try! c.call(["Test"])

print(ret) // #=> "Test"