Swift 中的函数数组 [英] Array of functions in Swift

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

问题描述

如何像在 JavaScript 中那样将一组函数存储在稍后回调的数组中?Any 和 AnyObject 类型不能保存具有不同类型方法签名的函数.

How can I store an array of functions to callback later in an array like in JavaScript? Any and AnyObject type cannot hold functions with different types of method signatures.

推荐答案

您可以使用枚举将各种函数放入 Array 中,然后使用 switch 提取函数.

You can use an enum to put various functions into the Array and then extract the functions with a switch.

    enum MyFuncs {
        case Arity0 ( Void -> Void )
        case Arity2 ( (Int, String) -> Void)
    }

    func someFunc(n:Int, S:String) { }
    func boringFunc() {}
    var funcs = Array<MyFuncs>()
    funcs.append(MyFuncs.Arity0(boringFunc))
    funcs.append( MyFuncs.Arity2(someFunc))

    for f in funcs {
        switch f {
        case let .Arity0(f):
            f()  // call the function with no arguments
        case let .Arity2(f):
            f(2,"fred") // call the function with two args
        }
    }

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

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