Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to cast "AnyObject" to a swift struct

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"}]
like image 961
Avner Barr Avatar asked Nov 10 '22 14:11

Avner Barr


1 Answers

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/

like image 119
ogres Avatar answered Nov 15 '22 07:11

ogres