Skip to content

Instantly share code, notes, and snippets.

@tarunon
Last active May 7, 2016 13:26
Show Gist options
  • Save tarunon/645bfdadf43bf7583c00a099a2ae2e2a to your computer and use it in GitHub Desktop.
Save tarunon/645bfdadf43bf7583c00a099a2ae2e2a to your computer and use it in GitHub Desktop.
dynamic invocation in swift
func wrap<A, B, C>(f: A -> B -> C) -> (A -> Any -> Any) {
return { a1 in { a2 in f(a1)(a2 as! B) } }
}
protocol Dynamic {
static var functions: [Selector: Self -> Any -> Any] { get }
func dynamicInvoke(f: Selector, arg: Any) -> Any
}
extension Dynamic {
func dynamicInvoke(f: Selector, arg: Any) -> Any {
return Self.functions[f]?(self)(arg)
}
}
final class A: Dynamic {
static var functions: [Selector : A -> Any -> Any] = [
#selector(A.a): wrap(A.a),
#selector(A.b(_:)): wrap(A.b),
#selector(A.c(_:c2:)): wrap(A.c)
]
@objc func a() {
print("a")
}
@objc func b(b: String) {
print(b)
}
@objc func c(c: String, c2: Int) {
for _ in 0..<c2 {
print(c)
}
}
}
A().dynamicInvoke(#selector(A.a), arg: ())
A().dynamicInvoke(#selector(A.b(_:)), arg: "b")
A().dynamicInvoke(#selector(A.c(_:c2:)), arg: ("c", 2))
@tarunon
Copy link
Author

tarunon commented May 7, 2016

微妙

@MarcSteven
Copy link

Great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment