创建一个可选块作为变量

时间:2023-02-08 11:13:14

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,所以我没有收到这个错误?

2 个解决方案

#1


25  

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. Try writing it like this instead:

编写它的方式,编译器假定progressBlock是一个闭包,它返回一个可选的空元组而不是一个返回空元组的可选闭包。尝试这样写:

class MyObject:NSObject {
    var progressBlock:((progress:Double) -> ())?
    init() {
        progressBlock = nil
        progressBlock = { (Double) -> () in /* code */ }
    }
}

#2


4  

Adding to connor's reply. An optional block can be written as:

添加到connor的回复。可选块可写为:

var block : (() -> ())? = nil

Or as an explicit Optional:

或者作为一个明确的可选:

var block : Optional<() -> ()> = nil

Or better yet, with a custom type

或者更好的是,使用自定义类型

typealias BlockType = () -> ()

var block : BlockType? = nil

#1


25  

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. Try writing it like this instead:

编写它的方式,编译器假定progressBlock是一个闭包,它返回一个可选的空元组而不是一个返回空元组的可选闭包。尝试这样写:

class MyObject:NSObject {
    var progressBlock:((progress:Double) -> ())?
    init() {
        progressBlock = nil
        progressBlock = { (Double) -> () in /* code */ }
    }
}

#2


4  

Adding to connor's reply. An optional block can be written as:

添加到connor的回复。可选块可写为:

var block : (() -> ())? = nil

Or as an explicit Optional:

或者作为一个明确的可选:

var block : Optional<() -> ()> = nil

Or better yet, with a custom type

或者更好的是,使用自定义类型

typealias BlockType = () -> ()

var block : BlockType? = nil