Can someone explain what completionHandler: ((Bool) -> Void) means?
For instance it appears when requesting camera access:
AVCaptureDevice.requestAccess(for: AVMediaType.depthData, completionHandler: (<#T##(Bool) -> Void#>))
I usually do this to check if access was granted or not:
func requestCamera() {
AVCaptureDevice.requestAccess(for: AVMediaType.video) { (response) in
if response {
print("true")
} else {
print("denied")
}
}
}
Obviously I do stuff there, but that doesn't matter here. I just want to understand what ((Bool) -> Void) means and why I have to use the completion handler here. With other functions I can just set the handler to nil, but in this case it expects a response in some way.
So what does this mean?
Read Closures section of the Swift documentation.
It is a completion closure that gets executed when the AVCaptureDevice.requestAccess is finished with requesting access from the user. It has one Bool parameter that is true/false according to whether the user granted the access or not. It is not optional, so you have to provide some closure - that was a decision of the AVCaptureDevice.requestAccess author, and it makes sense - if you are requesting the access, you are requesting it because you want to use AVCaptureDevice. Therefore the author expects you to react to completing the requestAccess in some way.
Closure expression syntax has the following general form:
{ (parameters) -> return type in
statements
}
The parameters in closure expression syntax can be in-out parameters, but they can’t have a default value. Variadic parameters can be used if you name the variadic parameter. Tuples can also be used as parameter types and return types.
completionHandler: ((Bool) -> Void) this means that you'll get a Boolean value in your closure and it will return nothing(Void). Just like a method.
You can find this more about in Apple's documentation about closures
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