Swift: executing a function as a parameter

I am trying to accomplish the following task (using a game board): store a list of functions in an array and then execute them.

What am I doing:

func f1(){
    println("f1")
}

var a : [(a: Int, b: (Void) -> Void)] = []

a.append(a: 2, b: f1)

for(var i = a.count-1; i >= 0; i--){
    a[i].b()
}

      

The error I am getting is the following: "Execution was aborted, reason: EXC_BAD_ACCESS (code = EXC_I386_GPFLT)" on call only:

a[i].b()

      

while if I type:

a[i].b 

      

The playground will prompt me: "(Function)"

Any idea on how I can do this? How can I execute the function? Thanks to


Even though Swift seems to prefer "No change", the issue seems to be resolved with the new Swift 1.2 release (In my tests that only worked with unnamed tuples)

+3


source to share


1 answer


It definitely smells like a bug. Expanding the expression it runs without issue in the storyboard:

for(var i = a.count-1; i >= 0; i--){
    let element = a[i]
    let method = element.b
    method()
}

      

This is probably due to closures when used in tuples.



I have verified that removing an integer value from a tuple works:

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

a.append(f1)

for(var i = a.count-1; i >= 0; i--){
    a[i].0()
}

      

Inverting the order (close first, integer) has no effect.

+1


source







All Articles