0

Here's a block type that I am defining in objective-c

typedef void (^arrayBlock)(NSArray *blockArray);

I have an objective-c class with a method that uses this as a return block

-(void)loadTimesWithSuccessBlock:(arrayBlock)successBlock;

When I try to use this method in Swift, this is what autocomplete gives me.

let timeClockLibrarian = HMFTimeClockLibrarian()
timeClockLibrarian.loadTimesWithSuccessBlock { ([AnyObject]!) -> Void in
   //Where is blockArray?         
}

I'm assuming that [AnyObject]! is supposed to be the NSArray. But I don't see how I'm supposed to get access to that variable?

If I were to use this method in Objective-C I get a result like this:

[timeClockLibrarian loadTimesWithSuccessBlock:^(NSArray *blockArray) {
        //I can use the blockArray here :)
}];

2 Answers 2

1

[AnyObject]! is indeed only the type of the variable; autocomplete didn't name it. You just need to do something like (blockArray: [AnyObject]!).

let timeClockLibrarian = HMFTimeClockLibrarian()
timeClockLibrarian.loadTimesWithSuccessBlock { (blockArray: [AnyObject]!) -> Void in
   // your code here
}
Sign up to request clarification or add additional context in comments.

5 Comments

That's what I thought. When I try to assign blockArray to a local variable i.e.{ var logEntries = [LogEntry() } using { self.logEntries = blockArray } it tells me "Cannot invoke 'loadTimesWithSuccessBlock' with an argument list of type '(([AnyObject]!) -> Void)'"
That's because the array is untyped and the assignment fails. You have different options depending on whether you use Xcode 6 or an Xcode 7 beta.
IIRC, that should be self.logEntries = blockArray as [LogEntry].
Just tried it, and it wanted me to use as! instead of as. I'm not sure what that means, but it compiles now.
I wasn't sure which syntax was the correct syntax on Xcode 6, my bad. Glad it works. Also, at some point in the evolution of Xcode, it becomes possible to change the typedef on the Objective-C type to void (^arrayBlock)(NSArray<LogEntry>* __nonnull blockArray) or something along these lines, which lets Swift bridge the argument into a [LogEntry] without further complications.
0

Write like this:

let timeClockLibrarian = HMFTimeClockLibrarian()
timeClockLibrarian.loadTimesWithSuccessBlock { blockArray in
   doSomething(blockArray)
}

If you want to refer to weak self use this:

let timeClockLibrarian = HMFTimeClockLibrarian()
timeClockLibrarian.loadTimesWithSuccessBlock { [weak self] blockArray in
   self?.doSomething(blockArray)
}

You may also want to get rid of implicit unwrapping. If so, specify nullability in Obj-C code:

typedef void (^arrayBlock)(nullable NSArray *blockArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.