Last active
May 7, 2016 13:26
-
-
Save tarunon/645bfdadf43bf7583c00a099a2ae2e2a to your computer and use it in GitHub Desktop.
dynamic invocation in swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
微妙