简体   繁体   中英

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.

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

I think it should be something like this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM