Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure default initializer missing - swift closure variable declaration?

I declared closure outside viewController class, I created one variable of that closure inside viewController class, but it shows the error of default initializer missing for this closure.

I understand the consequences about variable and constant declaration and default initialization have to be assigned at the time of declaration. but I unable to understand what could be the default initialization of my closure, I tried bunch of few tricks to solve it but didn't worked out.

Here is my closure declaration

typealias completionBlock = (String) -> ()  

and here is my variable declaration of that closure, which prompting to initialize it.

class ViewController: UIViewController {

     var completionHandler: completionBlock = // What could be the default initializer to this closure

     override func viewDidLoad() {
         super.viewDidLoad()
     }
}

I want to achieve calling this block whenever I gets those values required to pass, Same as objective-c external completionBlock declaration.

like image 683
Kiran Jasvanee Avatar asked Mar 14 '23 13:03

Kiran Jasvanee


2 Answers

You have 3 Options

  • default property:

    var completionHandler : completionBlock = { _ in }
    
  • Implicitly unwrapped Optional - only do this when you are 100% sure a value will be set before ever calling the completionHandler:

    var completionHandler: completionBlock!
    
  • "regular" Optional

    var completionHandler: completionBlock?
    
    // later callable via
    completionHandler?("hi")
    
like image 82
luk2302 Avatar answered Apr 06 '23 18:04

luk2302


I think it should be something like this?

var completionHandler: completionBlock = { stringValue  in 
        // but your code here
    }
like image 34
Ismail Avatar answered Apr 06 '23 17:04

Ismail