8

I have a third party Objective-C library in my swift project, in one of the .h files, it has a typedef:

typedef void (^YDBlutoothToolContectedList) (NSArray *);

and inside the class, it has a property:

@property (nonatomic, copy) YDBlutoothToolContectedList blutoothToolContectedList;

(please ignore its spelling)

When I try to use this property in my swift class, I use

bt.blutoothToolContectedList = {(_ tempArray: [Any]) -> Void in
    self.devices = tempArray
    self.tableView.reloadData()
}

and I got the error says:

Cannot assign value of type '([Any]) -> Void' to type 'YDBlutoothToolContectedList!'

I know the above Objective-C code in swift would be:

typealias YDBlutoothToolContectedList = () -> Void

but I can't re-write that Objective-C file and swift can't cast the closure type, is there a possible way to solve this problem?

1 Answer 1

13
typedef void (^YDBlutoothToolContectedList) (NSArray *);

is mapped to Swift as

public typealias YDBlutoothToolContectedList = ([Any]?) -> Swift.Void

because the closure parameter can be nil. (You can verify that by selecting the .h-file and then choosing Navigate->Jump to Generated Interface in the Xcode menu.)

Therefore the correct assignment would be

bt.blutoothToolContectedList = {(_ tempArray: [Any]?) -> Void in
    // ...
}

or simply let the compiler infer the parameter type:

bt.blutoothToolContectedList = { tmpArray in
    // ...
}

If you could add a nullability annotation to the Objective-C definition:

typedef void (^YDBlutoothToolContectedList) (NSArray  * _Nonnull );

then it would be mapped to Swift as

public typealias YDBlutoothToolContectedList = ([Any]) -> Swift.Void
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I don't have much OC experience, so sometimes it's difficult for me to read some of the OC source codes and try to convert them into Swift.
@SensEyeNULL: You are welcome! Does this answer your question? Please let me know if you need more information.

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.