[英]Create an optional block as a variable
I have a simple class where I declare a block as a variable: 我有一个简单的类,其中将一个块声明为变量:
class MyObject : NSObject
{
var progressBlock:(progress:Double) -> ()?
init() { }
}
As far as I understand, if defined this way, progressBlock
does not have to be initialized in the init()
initializer 据我了解,如果以这种方式定义,则无需在
init()
初始化程序中初始化progressBlock
However, when I try to compile I get his error: 但是,当我尝试编译时,出现了他的错误:
Property 'self.progressBlock' not initialized at super.init
So the question is, how do I create an optional progressBlock
, so I don't get this error? 所以问题是,如何创建可选的
progressBlock
,这样就不会出现此错误?
The way you have written it, the compiler assumes progressBlock is a closure that returns an optional empty tuple instead of an optional closure that returns an empty tuple. 编写方式,编译器假定progressBlock是一个返回一个可选的空元组的闭包,而不是一个返回一个空元组的可选闭包。 Try writing it like this instead:
尝试像这样编写它:
class MyObject:NSObject {
var progressBlock:((progress:Double) -> ())?
init() {
progressBlock = nil
progressBlock = { (Double) -> () in /* code */ }
}
}
Adding to connor's reply. 添加到康纳的答复。 An optional block can be written as:
可选块可以写为:
var block : (() -> ())? = nil
Or as an explicit Optional
: 或作为明确的
Optional
:
var block : Optional<() -> ()> = nil
Or better yet, with a custom type 或者更好,使用自定义类型
typealias BlockType = () -> ()
var block : BlockType? = nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.