Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: What does "completionHandler: ((Bool) -> Void)" mean? [duplicate]

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?

like image 408
RjC Avatar asked Dec 06 '25 04:12

RjC


2 Answers

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.

like image 177
Milan Nosáľ Avatar answered Dec 07 '25 20:12

Milan Nosáľ


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

like image 21
Agent Smith Avatar answered Dec 07 '25 18:12

Agent Smith