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
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
}
}
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
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With