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?
You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.
Most of the core iOS and MacOs software is still written in Objective-C, though Apple is pushing for new updates to be written in Swift.
If you're interested in how to learn the Swift programming language, you might want to check out the guide for moving from Objective-C to Swift. What you should notice, though, is that there are two important differences between the Objective-C and Swift languages: Swift is not a strict superset of the C language.
If you want to get work done, Objective-C is the way to go. Swift is the new kid on the block, but it's still a kid. If you want to get work done, Objective-C is the way to go. At the time of writing, Apple's software development kits are primarily written in C and Objective-C.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With