Nico
Nico

Reputation: 6359

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

Upvotes: 8

Views: 6052

Answers (4)

Giang
Giang

Reputation: 2729

I wrote 2 version objective-c and swift5 to you can compare

Objective-C version

dispatch_block_t completionBlock = ^{
// run your code in completion block
}

// start task in background thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    // update completion block in main thread
    dispatch_async(dispatch_get_main_queue(),completionBlock);
};

Swift 5 version

let completionBlock: () -> Void = {[weak self] in
// run your code in completion block
// using `[weak self] in` to avoid memory leak 
}
// start task in background thread        
DispatchQueue.global().async {[weak self] in
   // update completion block in main thread
   DispatchQueue.main.async(execute: completionBlock)
}

Upvotes: 0

dengST30
dengST30

Reputation: 4037

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
};

Upvotes: 2

user3349433
user3349433

Reputation: 480

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

Upvotes: 1

Nate Cook
Nate Cook

Reputation: 93286

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
    }
}

Upvotes: 7

Related Questions