【问题标题】:(Reflection) Calling A Method With Parameters By Function Name In Swift(反思)在 Swift 中按函数名调用带参数的方法
【发布时间】:2020-05-10 21:18:31
【问题描述】:

上下文

我有一个名为Solution 的类实例,我有一个函数名作为字符串functionName,我想在Solution 实例solutionInstance 上调用它。我在数组中有函数的参数,我也想传递这些参数。

我正在使用 Swift 编译器将我所有的 .swift 文件一起编译(swiftc 带有一个枚举文件,然后是 -o 和输出文件名),然后我运行最终输出。

Python 示例

这是我在 Python 中的操作方式:

method = getattr(solutionInstance, functionName) # get method off of instance for function
programOutput = method(*testInputsParsed) # pass the list of parameters & call the method

目的

这是在容器中运行以运行用户代码的服务器端代码。此代码位于“驱动程序”main.swift 文件中,该文件调用方法并编排测试。

问题

Swift 是静态类型的,我一直在搜索,大多数消息来源说 Swift 中的反射支持有限(并建议“进入 Objective-C”以获得所需的功能)。

Swift 不是我的母语(TypeScript/JavaScript、Java、Python 最强,然后是 C# 和 C++ 温和,然后只是为这个功能实现 Swift 代码)所以我不确定这意味着什么,我还没有能够找到明确的答案。

问题

如何在Solution 类实例上通过函数名称调用函数(它没有实现任何协议,至少由我实现)并在 Swift 中传递参数数组(使用反射)?我的设置需要如何更改才能实现(导入库等)

谢谢!

参考帖子

【问题讨论】:

    标签: ios swift reflection


    【解决方案1】:

    首先,正如您所提到的,Swift 没有完整的反射功能,并且依赖于并存的 ObjC 来提供这些功能。

    所以即使你可以编写纯 Swift 代码,你也需要 SolutionNSObject 的子类(或实现 NSObjectProtocol)。

    游乐场样本:

    class Solution: NSObject {
    
        @objc func functionName(greeting: String, name: String) {
            print(greeting, name)
        }
    
    }
    
    let solutionInstance = Solution() as NSObject
    let selector = #selector(Solution.functionName)
    if solutionInstance.responds(to: selector) {
        solutionInstance.perform(selector, with: "Hello", with: "solution")
    }
    

    这里还有其他的关注点:

    • Swift 的 perform 仅限于 2 个参数
    • 您需要拥有该方法的确切签名(此处为#selector)

    如果您可以在第一个参数中添加一个数组,并且始终具有相同的签名,那么您就完成了。 但如果你真的需要更进一步,你别无选择,只能使用 ObjC,它在 Playground 中不起作用。

    您可以创建类似的 Driver.m 文件:

    #import <Foundation/Foundation.h>
    #import <objc/runtime.h>
    
    id call (NSObject *callOn, NSString *callMethod, NSArray <NSObject *>*callParameters)
    {
        void *result = NULL;
        unsigned int index, count;
    
        Method *methods = class_copyMethodList(callOn.class, &count);
        for (index = 0; index < count; ++index)
        {
            Method method = methods[index];
    
            struct objc_method_description *description = method_getDescription(method);
            NSString *name = [NSString stringWithUTF8String:sel_getName(description->name)];
            if ([name isEqualToString:callMethod])
            {
                NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:description->types];
                NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    
                NSObject *parameters[callParameters.count];
                for (int p = 0; p < callParameters.count; ++p) {
                    parameters[p] = [callParameters objectAtIndex:p];
                    [invocation setArgument:&parameters[p] atIndex:p + 2]; // 0 is self 1 is SEL
                }
                [invocation setTarget:callOn];
                [invocation setSelector:description->name];
                [invocation invoke];
                [invocation getReturnValue:&result];
                break;
            }
        }
        free(methods);
    
        return (__bridge id)result;
    }
    

    将其添加到桥接头(以便 Swift 了解 ObjC 中的内容):

    // YourProjectName-Bridging-Header.h
    id call (NSObject *callOn, NSString *callMethod, NSArray *callParameters);
    

    然后用这样的 Solution.swift 调用它:

    import Foundation
    
    class Solution: NSObject {
    
        override init() {
            super.init()
            // this should go in Driver.swift
            let result = call(self, "functionNameWithGreeting:name:", ["Hello", "solution"])
            print(result as Any)
        }
    
        @objc
        func functionName(greeting: String, name: String) -> String {
            print(greeting, name)
            return "return"
        }
    
    }
    

    输出:

    Hello solution
    Optional(return)
    

    编辑:编译

    要在命令行上同时编译 ObjC 和 Swift,您可以先将 ObjC 编译为目标文件:

    $ cc -O -c YouObjCFile.m
    

    然后使用桥接头和目标文件编译您的 Swift 项目:

    $ swiftc -import-objc-header ../Your-Bridging-Header.h YouObjCFile.o AllYourSwiftFiles.swift -o program
    

    working sample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 2021-02-06
      相关资源
      最近更新 更多