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