我实现了一个简单的委托模式,我需要在主队列中调用委托方法。这是执行此调用的代码:
dispatch_async(dispatch_get_main_queue()){
self.delegate?.readerDidCompleteDownload(self, data: tempData)
}
但由于此错误我无法编译
Could not find member: readerDidCompleteDownload:
该方法在委托中实现,协议正确定义
@objc protocol DBDataReaderDelegate{
func readerDidCompleteDownload(reader: DBDataReader, data:String[])
@optional func readerDidFailDownload(reader: DBDataReader)
}
如果我在dispatch_async
之外调用此方法,它可以正常工作。
我做错了什么?!
我在NSURLSessionDownloadDelegate函数中调用此方法...我在此报告完整代码只是为了向此问题添加更多信息:
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!){
let data = NSData(contentsOfURL: location)
var error:NSError
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
if let JSONObj:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? NSDictionary {
var tempData:String[] = String[]()
if let shots = JSONObj["shots"] as? NSDictionary[]{
for (index, element) in enumerate(shots){
if let title:String = element["title"] as? String{
tempData += title
}
}
dispatch_async(dispatch_get_main_queue()){
self.delegate?.readerDidCompleteDownload(self, data: tempData)
}
}
}else{
delegate?.readerDidFailDownload?(self)
}
}
答案 0 :(得分:1)
„The type of this function is () -> (), or “a function that has no parameters,
and returns Void.” Functions that don’t specify a return value always
return Void, which is equivalent to an empty tuple in Swift, shown as ().”
Apple Inc. „The Swift Programming Language”. iBooks
因为委托是可选类型并且可以是nil,并且Swift中的每个函数或方法都必须返回值,例如Void!,(),你只需要在dispatch_async的末尾添加元组()
dispatch_async(dispatch_get_main_queue()){
self.delegate?.readerDidCompleteDownload(self, data: tempData)
()
}
答案 1 :(得分:1)
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.delegate?.readerDidCompleteDownload(self, data: tempData)
}
没有() -> Void in
,Swift推断出闭包的类型。推断结果来自“optional chaining”readerDidCompleteDownload
,因此它是Void?
。这使得推断的闭包类型() -> Void?
(可选的Void)与dispatch_block_t
不同:() -> Void
(非可选的Void)。
这可以在Swift中使用一些语法糖。