如何使用nil作为空闭包参数?

时间:2016-10-13 16:08:15

标签: swift3

我有一个数据加载函数,有时需要通过回调更新ui:

class Middleware {
    ...
    func loadChannels(callback: @escaping (_ middleware: Middleware) -> Void) {
        let url = URL(string: uri + "/entity.json")!
        let task = URLSession.shared.dataTask(with: url) {
            (data, response, error) in

            guard let data = data, let _:URLResponse = response , error == nil else {
                print("> loadChannels " + error.debugDescription)
                return
            }

            let json = JSON(data: data)

            if (json["entities"].array != nil) {
                self.channels.removeAll()

                for (_, json) in json["entities"] {
                    if let channel = Channel(json: json) {
                        self.channels += [channel]
                    }
                }

                if (callback != nil) {
                    callback!(self)
                }
            }
        }

        task.resume()
    }
}

当我不需要回拨时,我会这样称呼它:

middleware.loadChannels(callback: { (middleware: Middleware) -> Void in })

使用

middleware.loadChannels(callback: nil)

不起作用:

  

Nil与预期的参数类型不兼容'(中间件) - >空隙'

是否有比我当前版本更简洁的方式?

1 个答案:

答案 0 :(得分:0)

您需要将回调设为可选:

func loadChannels(callback: ((_ middleware: Middleware) -> Void)?) {
}

现在,您可以将nil传递给callback参数。