[swift-evolution] [Discussion] Type for matching a closure

Charlie Monroe charlie at charliemonroe.net
Tue May 31 05:12:26 CDT 2016


AFAIK there isn't currently a way of matching if an Any instance is a closure:

func something<T>(x: T) -> String {
    /// is x a function? We want to support Any (Int, Int32, Float, Double,
    ///  AnyObject, ...), but disallow functions.
    ...
}

let myClosure = { print("Hello") }
something(myClosure) // Don't allow this.


I propose adding a protocol Function - all closures would conform to it. See the code on 

https://gist.github.com/charlieMonroe/655f2b5e25cc0b4ba06c0ddafa41c73b <https://gist.github.com/charlieMonroe/655f2b5e25cc0b4ba06c0ddafa41c73b>

which outlines the API and possible usage of it:

- Allowing to match a function from an Any instance.
- Inspect the function object - arguments, captured values, return type. This may help debugging retain cycles by printing the catputred variables - you will be able to see `self` within these.
- Invocation - creating something as NSInvocation, since you'd be able to call the function with a list of arguments.
- This could also become a basis for some RPC in Swift.

I know this is partially something for the Reflection discussion going on here as well as something for the existentials, but since it kind of overlapses both discussions, I thought creating a new thread would perhaps be beneficial.

Charlie

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160531/96becfca/attachment.html>


More information about the swift-evolution mailing list