【发布时间】:2015-01-05 03:47:39
【问题描述】:
我想在 swift 项目中实现回调,就像我在 Objective-C 中所做的那样 我需要一个闭包类型的变量。该闭包应该将对象作为参数并且不返回任何内容。
var downloadCompleted: (MLBook) -> (Void)!
当我需要触发回调时,我会这样做:
if self.downloadCompleted {
self.downloadCompleted(book)
}
编译器报错:
Type '(MLBook) -> (Void)!' does not conform to protocol 'BooleanType'
如果我删除 if 语句,编译器会说:
Property 'self.downloadCompleted' not initialized
即使它是隐式展开的。
当我尝试获取回调时:
BookStore.sharedInstance.downloadCompleted{(book: MLBook) -> () in
println("Print if you got the callback")
}
我收到此错误消息:
'(MLBook) -> ()' is not convertible to 'MLBook'
我更担心最后一条错误消息,因为我不太确定它试图告诉我什么。
任何帮助将不胜感激。谢谢
【问题讨论】:
标签: variables swift callback closures