功能序列有问题 [英] Any or a trouble with sequence of functions

查看:64
本文介绍了功能序列有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的问题是我需要创建一系列可以调用的函数,但是面临的问题是,即使一个函数是一等成员并且确实符合协议 Any ,则下面的代码不起作用.

The problem I have faced is that I need to make a sequence of functions that can be invoked, but faced a problem that is, even though a function is a first-class member and do conform to protocol Any, the code bellow does not work.

struct FunctionSequence {

    var callbacks = [Any]() //how to restrict Any to only functions?

    init(with functions: Any...){
        self.callbacks = functions
    }

    func callAll(){
        for f in callbacks {
            f()
        }
    }
}

编译中断:

error: cannot call value of non-function type 'Any'

因此,我想请速战速决的人寻求帮助.PS我需要的结果如下:

So I ask people who's deep in the swift for some help. PS The result I need is as following:

var printer = FunctionSequence
    .init(with: {print("Hello,")}, {print("world!")})
printer.callbacks.insert({print("I hate you,")}, at: 1)
printer.callAll()
//outputs "Hello, I hate you, world!"

推荐答案

没有通用的函数类型"-具有不同参数或不同返回类型的函数是不同类型.

There is no general "function type" – functions with different arguments or different return types are different types.

在您的情况下,您显然想要一个类型为()->>的函数数组.无效,即不带参数且不返回值的函数:

In your case you apparently want an array of functions of type () -> Void, i.e. functions that take no arguments and do not return a value:

struct FunctionSequence {

    var callbacks = [() -> Void]()

    init(with functions: (() -> Void)...){
        self.callbacks = functions
    }

    // ...
}

或具有类型别名:

typealias SimpleFunction = () -> Void

struct FunctionSequence {

    var callbacks = [SimpleFunction]()

    init(with functions: SimpleFunction...){
        self.callbacks = functions
    }

    // ...
}

如果将 callbacks 定义为 Any 的数组,则可以在其中添加任何内容:不带参数的函数,带一个整数的函数,...,整数,字符串,任何东西.

If callbacks is defined as an array of Any then you can put anything in it: functions taking no arguments, functions taking one integer, ..., integers, strings, anything.

然后可以检查每个数组元素是否具有特定签名,并相应地调用函数.示例:

It is then possible to check each array element for a specific signature, and call the functions accordingly. Example:

struct FunctionSequence {

    var callbacks = [Any]()

    init(with functions: Any...){
        self.callbacks = functions
    }

    func callAll() {
        for f in callbacks {
            switch f {
            case let f0 as () -> Void:    f0()
            case let f1 as (Int) -> Void: f1(17)
            default: break // Other function signature, or not a function at all.
            }
        }
    }
}

let printer = FunctionSequence(with:
        { print("Hello,") },
        { (i: Int) in print(i)} )
printer.callAll()

这篇关于功能序列有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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