无法为使用typedef的块编写正确的语法

时间:2014-08-29 15:06:35

标签: objective-c swift

我有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提供的模板:

enter image description here

这就是我的尝试:

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) -> ()

下一步是什么?

如何让它发挥作用?

谢谢,

1 个答案:

答案 0 :(得分:1)

查看docs有关如何使用Cocoa和Core Foundation的信息。

这应该有效:

abHelper.createAddressBook() {
    (addrBook:ABAddressBook?, errCode:CDVAddressBookAccessError!) in                

            if addrBook == nil  {

            }


    }