5

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"}]
Avba
  • 14,822
  • 20
  • 92
  • 192

2 Answers2

1

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/

ogres
  • 3,660
  • 1
  • 17
  • 16
0

You can't use anyObject to represent structs. You can only use AnyObject with class instances.

You can try your chance with Any, which can represent any type of instances including function types.

Salihcyilmaz
  • 326
  • 1
  • 3
  • 11