prawn
prawn

Reputation: 2653

store an array of functions with closures

My goal is to have an array of functions that execute one after the other.

static func GetData(success:(() ->())?, failure:((response : NSURLResponse, error : NSError) ->())?){
       //do something asynchronous. make web service call

       success?()
      //or
      failure?(response: urlResponse, error: errorThrown) 
}

And then in a view controller, I'm trying to store functions similar to this one above in an array. My goal is to iterate through this array and execute the functions one after the other. The reason for this is because each function is dependent on the data that gets returned from the previous function.

So I made an enum

    enum MyEnum {
    case GetData()
    case GetData2()...and so on
    //and every other function is put here
}

Now in my view controller, I add this to an array

funcs.append(MyEnum.GetData(DataAccess.GetData({
        //do stuff

        }, failure: { (response, error) in

    })))

funcs.append(MyEnum.GetData2(DataAccess.GetData2({
            //do stuff

            }, failure: { (response, error) in

        })))

However, whenever I store a function, it automatically executes. I think I could do it if there weren't any closures but I need them to determine how to proceed.

Is there a better way of doing this? Am I missing something?

Storing an array of functions with closures automatically executes them

var arrayOfFuncs = [
        DataAccess.GetData1({
            print("success")
            }, failure: { (response, error) in
                print("failure")
        }),

        DataAccess.GetData2({
            print("ok")
            }, failure: { (response, error) in
                print("ee")
        })
    ]

Upvotes: 0

Views: 803

Answers (1)

Andrew Bradnan
Andrew Bradnan

Reputation: 36

GetData takes 2 closures as parameters, it's not two closures. I don't get what you are doing with the enum.

typealias Block = () -> Void
typealias Error = (NSURLResponse,NSError) -> Void

var funcs = [(Block,Error)]

func.forEach{ f => f._0() } // call success()


// Or you could do this
typealias Getter = (Block,Error) -> Void
var funcs2 = [Getter]
funcs2.append(DataAccess.GetData)

Upvotes: 1

Related Questions