如何创建函数数组?

时间:2021-01-13 21:35:36

I'm trying to build out a basic implementation of Promises in Swift, and I need to be able to add functions to an array, but I'm not sure how to get that to work.

我正在尝试在Swift中构建Promises的基本实现,并且我需要能够向数组添加函数,但我不确定如何使其工作。

class Promise {
    var pending = []

    func resolve() -> Void {
    }

    func then(success: (Void -> Void)) -> Promise {
        // how do I add success to pending array?
        return self
    }
}

let p = Promise()
p.then({println("finished")})

What I'm finding is that the Swift Playground won't suggest append when I try to do something like this:

我发现当我尝试做这样的事情时,Swift Playground不建议追加:

self.pending.append(success)

self.pending.append(成功)

Which makes sense - Swift can't infer the type of self.pending - but that's where my problem lies. I'm not sure how to predefine an array of (Void -> Void) functions.

这是有道理的 - 斯威夫特不能推断自我的类型 - 但这就是我的问题所在。我不确定如何预定义一个(Void - > Void)函数数组。

Is it possible to create an array of functions in Swift? I would assume so, with functions being first-class citizens.

是否可以在Swift中创建一个函数数组?我会假设,功能是一等公民。

2 个解决方案

#1


24  

It's definitely possible, just initialize the array as:

这绝对是可能的,只需将数组初始化为:

var pending = Array<(Void -> Void)>()

or even a fancier

甚至是一位鸽友

var pending = Array<()->()>()

or

要么

var pending: [(Void->Void)] = []

or

要么

var pending: [(()->())] = []

or

要么

var penguins: [<(") <(")] = [] // kidding

#2


4  

This should work:

这应该工作:

var pending: (() -> ())[]

#1


24  

It's definitely possible, just initialize the array as:

这绝对是可能的,只需将数组初始化为:

var pending = Array<(Void -> Void)>()

or even a fancier

甚至是一位鸽友

var pending = Array<()->()>()

or

要么

var pending: [(Void->Void)] = []

or

要么

var pending: [(()->())] = []

or

要么

var penguins: [<(") <(")] = [] // kidding

#2


4  

This should work:

这应该工作:

var pending: (() -> ())[]