使用swift使用字符串进行动态方法调用

时间:2022-04-28 20:49:04

Does swift support the ability to call a method using a string?

swift是否支持使用字符串调用方法的能力?

I'll steal a great example from http://pilky.me/21/ to illustrate what I'd like to be able to do in swift. This is a trivial example, but for some design patterns this capability if very powerful and is supported in many other popular languages.

我将从http://pilky.me/21/中窃取一个很好的例子来说明我希望能在swift中做些什么。这是一个简单的例子,但对于某些设计模式,这种功能非常强大并且在许多其他流行语言中得到支持。

- (void)parseObject:(id)object {
    for (id data in object) {
        if ([[data type] isEqualToString:@"String"]) {
            [self parseString:[data value]]; 
        } else if ([[data type] isEqualToString:@"Number"]) {
            [self parseNumber:[data value]];
        } else if ([[data type] isEqualToString:@"Array"]) {
            [self parseArray:[data value]];
        }
    }
}

- (void)parseObjectDynamic:(id)object {
    for (id data in object) {
        [self performSelector:NSSelectorFromString([NSString stringWithFormat:@"parse%@:", [data type]]) withObject:[data value]];
    }
}

- (void)parseString:(NSString *)aString {}
- (void)parseNumber:(NSString *)aNumber {}
- (void)parseArray:(NSString *)aArray {}

As you can see, you can replace 7 line if statement with a single line. And the benefit is that if you need to support a new type in the future, you just add the new method, rather than have to remember to add an extra else if to your main parse method.

如您所见,您可以用一行代替7行if语句。并且好处是,如果您将来需要支持新类型,您只需添加新方法,而不必记住在主解析方法中添加额外的其他内容。

I understand you can call a block dynamically.

我知道你可以动态调用一个块。

There is a similar SO question here, but does not address how to do it in swift with strings: Alternative to performSelector in Swift?

这里有一个类似的SO问题,但没有解决如何使用字符串快速执行它:替代Swift中的performSelector?

1 个解决方案

#1


1  

It seems like performSelect isn't part of the runloop with Swift. It might just come in a later seed https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/index.html#//apple_ref/occ/instm/NSRunLoop/performSelector:target:argument:order:modes:

似乎performSelect不是Swift的runloop的一部分。它可能只是后来的种子https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/index.html#//apple_ref/occ/instm/NSRunLoop/ performSelector:目标:参数:顺序:模式:

#1


1  

It seems like performSelect isn't part of the runloop with Swift. It might just come in a later seed https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/index.html#//apple_ref/occ/instm/NSRunLoop/performSelector:target:argument:order:modes:

似乎performSelect不是Swift的runloop的一部分。它可能只是后来的种子https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/index.html#//apple_ref/occ/instm/NSRunLoop/ performSelector:目标:参数:顺序:模式: