Q:

Adding a closure to a customButton in Swift

I'm trying to convert the following code in Obj-c to swift:
CustomButton.h
@property (nonatomic, copy) void (^defaultAction)();

CustomButton.m
- (void)executeTargetActionBlock {
      if (self.defaultAction)
           self.defaultAction();
}

- (void) initialize {
[self addTarget:self action:@selector(executeTargetActionBlock) forControlEvents:UIControlEventTouchUpInside];
}

This initializeMethod is called in the init method of CustomButton. 

A:

class CustomButton: UIButton {
    var defaultAction: (() -> Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.addTarget(self, action: "executeTargetActionBlock", forControlEvents: UIControlEvents.TouchUpInside)
    }

    func executeTargetActionBlock() {
        if let action = defaultAction {
            action()
        }
    }
}

