我有Objective-C代码,我尝试转换为Swift但失败了。
typedef void (^ CDVAddressBookWorkerBlock)(
ABAddressBookRef addressBook,
CDVAddressBookAccessError* error
);
@interface CDVAddressBookHelper : NSObject
{}
- (void)createAddressBook:(CDVAddressBookWorkerBlock)workerBlock;
@end
这是Objective-C实现:
CDVAddressBookHelper* abHelper = [[CDVAddressBookHelper alloc] init];
[abHelper createAddressBook:
^(ABAddressBookRef addrBook, CDVAddressBookAccessError* errorCode)
{
/* ...*/
}
];
如何在Swift中编写它?
来自文档:
{(parameters) -> (return type) in expression statements}
这是xCode提供的模板:
这就是我的尝试:
var abHelper:CDVAddressBookHelper = CDVAddressBookHelper()
abHelper.createAddressBook(
{(addrBook:ABAddressBookRef, errCode:CDVAddressBookAccessError) in
if addrBook == nil {
}
} )
错误:
Type 'ABAddressBook!' does not conform to protocol 'AnyObject'`
[编辑]
问候:swift-closure-declaration-as-like-block-declaration帖子我试着写typealias
:
typealias CDVAddressBookWorkerBlock = (addrBook:ABAddressBookRef, errCode:CDVAddressBookAccessError) -> ()
下一步是什么?
如何让它发挥作用?
谢谢,
答案 0 :(得分:1)
查看docs有关如何使用Cocoa和Core Foundation的信息。
这应该有效:
abHelper.createAddressBook() {
(addrBook:ABAddressBook?, errCode:CDVAddressBookAccessError!) in
if addrBook == nil {
}
}