3

I'm trying to accomplish the following task (using the playground): store in an array a list of functions and later execute them.

What I'm doing is:

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'm getting is the following: "Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)" just on the call:

a[i].b()

while if I type:

a[i].b 

Playground suggest me: "(Function)"

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


Even though Swift seems to prefer the Unnamed tuples the problem seems to be solved with the new Swift version 1.2 (In my tests that worked only with unnamed tuples)

3
  • 1
    You've made that example very hard to understand by using a twice. Can you not use proper words instead of a, a, and b. Commented Dec 4, 2014 at 18:10
  • 2
    Looks like a bug to me. Same exception here when running in Debug mode, and Xcode 6.1.1 crashes when compiling that in Release mode. Commented Dec 4, 2014 at 18:13
  • Seems fixed in Swift 1.2, I updated the question Commented Apr 10, 2015 at 14:59

1 Answer 1

1

That definitely smells like a bug. Decomposing the expression it runs without problems in storyboard:

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

It's probably something related to closures when used in tuples.

I verified that removing the integer value from the tuple, it works:

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

a.append(f1)

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

Inverting the order (closure first, integer last) has no effect instead.

Sign up to request clarification or add additional context in comments.

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.