I have a swift method which receives a struct as a parameter.
Since the structs aren't bridged to objective-c, this method is invisible in the bridging header.
I was forced to created a new "identical" method that receives "AnyObject
" instead of the struct the original method required.
Now I am tasked with instantiating the swift structs from "AnyObject
".
Is it possible to "cast" the "AnyObject
" to a swift struct in this case?
Am I forced to write boiler plate to construct a swift struct from the AnyObject
?
I can send an NSDictionary
representing the structs key-value pairs. Does this help in any way?
For instance :
Swift
struct Properties {
var color = UIColor.redColor()
var text = "Some text"
}
class SomeClass : UIViewController {
func configure(options : Properties) {
// the original method
// not visible from
}
func wrapObjC_Configure(options : AnyObject) {
// Visible to objective-c
var convertedStruct = (options as Properties) // cast to the swift struct
self.configure(convertedStruct)
}
}
Objective-c
SomeClass *obj = [SomeClass new]
[obj wrapObjC_Configure:@{@"color" : [UIColor redColor],@"text" : @"Some text"}]
You could use NSValue
and contain your struct in it, send NSValue and then get the struct value from it,
sample category for NSValue would be:
@interface NSValue (Properties)
+ (instancetype)valuewithProperties:(Properties)value;
@property (readonly) Properties propertiesValue;
@end
@implementation NSValue (Properties)
+ (instancetype)valuewithProperties:(Properties)value
{
return [self valueWithBytes:&value objCType:@encode(Properties)];
}
- (Properties) propertiesValue
{
Properties value;
[self getValue:&value];
return value;
}
@end
More about NSValue here - https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSValue_Class/
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