Kiran Jasvanee
Kiran Jasvanee

Reputation: 6554

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.

Upvotes: 4

Views: 934

Answers (2)

Ismail
Ismail

Reputation: 2818

I think it should be something like this?

var completionHandler: completionBlock = { stringValue  in 
        // but your code here
    }

Upvotes: 1

luk2302
luk2302

Reputation: 57114

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")
    

Upvotes: 6

Related Questions