4

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.

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:

self.pending.append(success)

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.

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

2
  • I haven't tried this, but does the obvious var pending: (Void->Void)[] = [] not work? Commented Jun 6, 2014 at 18:44
  • The Swift playground doesn't seem to like var pending = (Void -> Void)[] = [] Commented Jun 6, 2014 at 18:46

2 Answers 2

26

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
Sign up to request clarification or add additional context in comments.

8 Comments

or (Void -> Void)[]
(Void -> Void)[] doesn't work for me, but `Array<(Void -> Void)> works perfectly
If you want to get fancier you can use Array<()->()>()
@AlexWayne I meant var array: (() -> ())[] = [] or var array: (Void -> Void)[] = []
Neat! Here's a fuller complete working example: gist.github.com/Squeegy/5d5c73a373b0c4839280
|
4

This should work:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.