Blocks on Swift (animateWithDuration:animations:completion:) Blocks on Swift (animateWithDuration:animations:completion:) ios ios

Blocks on Swift (animateWithDuration:animations:completion:)


The completion parameter in animateWithDuration takes a block which takes one boolean parameter. In Swift, like in Obj-C blocks, you must specify the parameters that a closure takes:

UIView.animateWithDuration(0.2, animations: {    self.blurBg.alpha = 1}, completion: {    (value: Bool) in    self.blurBg.hidden = true})

The important part here is the (value: Bool) in. That tells the compiler that this closure takes a Bool labeled 'value' and returns Void.

For reference, if you wanted to write a closure that returned a Bool, the syntax would be

{(value: Bool) -> bool in    //your stuff}


The completion is correct, the closure must accept a Bool parameter: (Bool) -> (). Try

UIView.animate(withDuration: 0.2, animations: {    self.blurBg.alpha = 1}, completion: { finished in    self.blurBg.hidden = true})


Underscore by itself alongside the in keyword will ignore the input

Swift 2

UIView.animateWithDuration(0.2, animations: {    self.blurBg.alpha = 1}, completion: { _ in    self.blurBg.hidden = true})

Swift 3, 4, 5

UIView.animate(withDuration: 0.2, animations: {    self.blurBg.alpha = 1}, completion: { _ in    self.blurBg.isHidden = true})