如何在Swift中使用函数数组 [英] How to use an array of functions in Swift

查看:45
本文介绍了如何在Swift中使用函数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了所有可以在这里找到的有关函数数组的文章-太好了.我估计.但是这些帖子都没有显示出如何使用它们(至少没有显示我正在尝试做的事情).这就是我想要的-它们都可以使用相同的arg,但这不是必须的.

I have read all the posts I can find here about arrays of functions - great you can do it. I figured. But none of the posts show practically how to use them (at least not what I'm trying to do). Here's what I want - they can all take the same args, but that's not a requirement.

本文已结束,将允许我循环执行每个功能(满足第一个目标).
https://stackoverflow.com/a/24447484/11114752

This article is close, and will allow me to loop through to execute each function (which meets the first goal).
https://stackoverflow.com/a/24447484/11114752

但是...如果我想通过引用执行单个功能怎么办?换句话说,如何仅调用引用的Arity2函数-例如:

But... what if I want to execute a single function by reference? In other words, how to call just the referenced Arity2 function - for example:

// None of these work (with or without the parameter labels)
funcs.Arity2(n: 2, S: "Fred)    // value of type [MyFuncs] has no member .Arity2
funcs[Arity2](n: 2, S: "Fred")  // no exact matches to call in subscript
funcs[.Arity2](n: 2, S: "Fred") // Cannot call value of non-function type...

let fn = funcs.first(where: { a whole ton of permutations here to try to match Arity2 }) -- a whole lotta frustrating nope...

请帮助!我没有尝试过任何工作.预编译器只是绕圈而行,提出的建议不会成功,并且不会编译.

Help, please! Nothing I've tried works. The pre-compiler just goes in circles making suggestions that don't pan out and it will not compile.

首先使用数组的原因是我将拥有很多功能,而且我不知道它们的全部功能.本质上,我想要一种架构的插件类型.我可以在其中添加功能列表(最好是在类的扩展之内,但这是另一个问题..),并且不更改按顺序执行每个功能的处理循环.

The reason for the array in the first place is that I'm going to have a quite a few functions, and I don't know what they all are in advance. Essentially, I want a plugin type of architecture. Where I can add to the list of functions (ideally within an extension of the class, but that's another problem..) and not change the processing loop that executes each function in order.

推荐答案

我认为您需要类似的东西

I assume you need something like

    _ = funcs.first {
        if case let MyFuncs.Arity2(f) = $0 {
            f(2, "Fred")
            return true
        }
        return false
    }

这篇关于如何在Swift中使用函数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆