[英]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. 我在viewController类之外声明了闭包,我在viewController类中创建了该闭包的一个变量,但它显示了此闭包缺少的默认初始值设定项的错误。
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. 每当我获得传递所需的值时,我想实现调用此块,与objective-c external completionBlock声明相同。
You have 3 Options 你有3个选项
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
: 隐式解包可选 - 只有在100%确定在调用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.