0

I have Objective-C code that I try to convert to Swift but failed.

typedef void (^ CDVAddressBookWorkerBlock)(
    ABAddressBookRef         addressBook,
    CDVAddressBookAccessError* error
    );

@interface CDVAddressBookHelper : NSObject
{}

- (void)createAddressBook:(CDVAddressBookWorkerBlock)workerBlock;
@end

And this is Objective-C implementation:

 CDVAddressBookHelper* abHelper = [[CDVAddressBookHelper alloc] init];
 [abHelper createAddressBook: 
       ^(ABAddressBookRef addrBook, CDVAddressBookAccessError* errorCode) 
        {
         /* ...*/
        }
 ];

How to write it in Swift?

From documentation:

{(parameters) -> (return type) in expression statements}

This is a template xCode offers:

enter image description here

This is what I tried:

var abHelper:CDVAddressBookHelper = CDVAddressBookHelper()

abHelper.createAddressBook(
        {(addrBook:ABAddressBookRef, errCode:CDVAddressBookAccessError) in

           if  addrBook == nil  {

           }
        } )

Error:

 Type 'ABAddressBook!' does not conform to protocol 'AnyObject'`

[EDIT]

Regards to: swift-closure-declaration-as-like-block-declaration post I tried to write typealias:

typealias CDVAddressBookWorkerBlock = (addrBook:ABAddressBookRef, errCode:CDVAddressBookAccessError) -> ()

What next?

How to make it work?

Thanks,

Community
  • 1
  • 1
snaggs
  • 5,543
  • 17
  • 64
  • 127

1 Answers1

1

Check out the docs about how to work with Cocoa and Core Foundation.

This should work:

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

            if addrBook == nil  {

            }


    }
Mike Pollard
  • 10,195
  • 2
  • 37
  • 46