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"}]
4

2 回答 2

1

您可以在其中使用NSValue并包含您的结构,发送 NSValue 然后从中获取结构值,

NSValue 的样本类别为:

@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

更多关于 NSValue 的信息 - https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSValue_Class/

于 2015-11-05T14:23:20.260 回答
0

您不能使用 anyObject 来表示结构。您只能将 AnyObject 与类实例一起使用。

您可以尝试使用 Any,它可以表示任何类型的实例,包括函数类型。

于 2015-04-28T13:35:56.687 回答