创建一个可选块作为变量 [英] Create an optional block as a variable

查看:99
本文介绍了创建一个可选块作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类,我将块声明为变量:

I have a simple class where I declare a block as a variable:

class MyObject : NSObject 
{
    var progressBlock:(progress:Double) -> ()?

    init() { }
}

至于我理解,如果以这种方式定义, progressBlock 不必在 init()初始值设定项中初始化

As far as I understand, if defined this way, progressBlock does not have to be initialized in the init() initializer

但是,当我尝试编译时,我得到了他的错误:

However, when I try to compile I get his error:

Property 'self.progressBlock' not initialized at super.init

所以问题是,我该如何创建一个可选的 progressBlock ,所以我没有收到此错误?

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

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

这篇关于创建一个可选块作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆