Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of dispatch_block_t in swift?

I have some objective-c code that I would like to understand in order to do the same in swift:

dispatch_block_t adjustTooltipVisibility = ^{
    self.tooltipView.alpha = _tooltipVisible ? 1.0 : 0.0;
    self.tooltipTipView.alpha = _tooltipVisible ? 1.0 : 0.0;
};

So far all I could find out about dispatch_block_t was that it's used in dispatch_after in swift as a closure. So I can understand that but I don't understand the use of it just like this in objective-c and how to transform this code into swift code

like image 411
Nico Avatar asked Apr 20 '15 02:04

Nico


3 Answers

dispatch_block_t is a type alias for a Void -> Void closure. Swift (as of version 1.2) doesn't infer those very well, so you'll need to declare the type. You'll also need to reference self explicitly to access instance properties, and will want to make sure you're not creating a reference cycle. Declaring self as weak in the closure is one safe approach:

let adjustTooltipVisibility: dispatch_block_t = { [weak self] in
    if self?._tooltipVisible == true {
        self?.tooltipView.alpha = 1
        self?.tooltipTipView.alpha = 1
    } else {
        self?.tooltipView.alpha = 0
        self?.tooltipTipView.alpha = 0
    }
}
like image 71
Nate Cook Avatar answered Nov 20 '22 17:11

Nate Cook


let adjustTooltipVisibility:Void->Void = {
    self.tooltipView.alpha = _tooltipVisible ? 1.0 : 0.0
    self.tooltipTipView.alpha = _tooltipVisible ? 1.0 : 0.0
};

If there will be something leading to retain cycle, you should use the unowned capture to self. The type of the block is Void->Void

like image 26
user3349433 Avatar answered Nov 20 '22 18:11

user3349433


In Swift 5,

dispatch_block_t is an alias for ()->Void


let adjustTooltipVisibility: ()->Void = {
    self.tooltipView.alpha = _tooltipVisible ? 1.0 : 0.0
    self.tooltipTipView.alpha = _tooltipVisible ? 1.0 : 0.0
};
like image 1
dengST30 Avatar answered Nov 20 '22 17:11

dengST30