Created
August 25, 2017 03:11
-
-
Save sindresorhus/50d1014b0e35be4675b6917719afb2de to your computer and use it in GitHub Desktop.
[Alternative] NSControl extension for closure version of `.action`
This file contains 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
class SelectorWrapper<T> { | |
let selector: Selector | |
let closure: (T) -> Void | |
init(withClosure closure: @escaping (T) -> Void) { | |
self.selector = #selector(callClosure) | |
self.closure = closure | |
} | |
@objc | |
private func callClosure(sender: AnyObject) { | |
closure(sender as! T) | |
} | |
} | |
var handle: Int = 0 | |
extension NSControl { | |
typealias ActionClosure = (NSControl) -> Void | |
var onAction: ActionClosure? { | |
get { | |
return nil | |
} | |
set { | |
if let newValue = newValue { | |
let selectorWrapper = SelectorWrapper<NSControl>(withClosure: newValue) | |
objc_setAssociatedObject(self, &handle, selectorWrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
action = selectorWrapper.selector | |
target = selectorWrapper | |
} else { | |
action = nil | |
target = nil | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice implementation