Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Slightly improved version of Beau Nouvelle's UIBarButtonItem closure extension. I hid all the helper classes within the extension and made them private, so as not to pollute the global namespace. Original article:
import Foundation
import UIKit
public extension UIBarButtonItem {
public typealias TargetClosure = (UIBarButtonItem) -> ()
public convenience init(title: String?, style: UIBarButtonItem.Style = .plain, closure: @escaping TargetClosure) {
self.init(title: title, style: style, target: nil, action: nil)
targetClosure = closure
action = #selector(UIBarButtonItem.closureAction)
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
private class ClosureWrapper: NSObject {
let closure: TargetClosure
init(_ closure: @escaping TargetClosure) {
self.closure = closure
private var targetClosure: TargetClosure? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? ClosureWrapper else {
return nil
return closureWrapper.closure
set {
guard let newValue = newValue else {
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
@objc private func closureAction() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment