1

I was working with swift and got a question from somewhere but didn't understand what output will I get while running the function.

import UIKit

var i = 0
var closureArray : [() -> ()] = []

for _ in 1...5{
    closureArray.append {
        print(i)
    }
    i += 1
}

what will I get when I will type:-

closureArray[0]()

I know the answer but i want to know the explanation behind it.

2
  • 2
    The Swift Language Guide explains it neatly. Check it out. Commented Jan 25, 2019 at 8:37
  • The closure body, print(i) for all the closures, will be executed (and i value evaluated) only after calling it (nothing new here). The key is that you are calling the closure after the loop so at that point the value of the var i is 5 and that's why all the closures body will have the same result "5". Commented Jan 25, 2019 at 9:48

3 Answers 3

3

You are appending functions body to closureArray with no return type as the function type has no input parameters and no return type.

So only closureArray will contains 5 blocks of functions.

Each element is itself a function with only one print operation which will print the array index. But if these are called after the for loop these always print the latest value of i

So closureArray[0]() will call the 0th indexed function that will print only "5" as the latest value of i is 5 and will return void.

Explanation is very simple.

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

Comments

0

This will always print 5 because you have defined a global variable, after traversing through the loop i=5. and after the loop, you are calling closure. which will always print 5. no matter the index of closureArray.

The value of i is only evaluated after calling closure.

Read Auto closure chapter swift4 guide:

https://docs.swift.org/swift-book/LanguageGuide/Closures.html

if you put closure calling inside for loop then it will print normally 'i' value i.e 0,1,2,3,4

for _ in 1...5{
    closureArray.append {
        print(i)
    }
    closureArray[0]()
    i += 1
}

Comments

0

The functions appended in the closureArray is print(i) every time and the value of i is incremented for each iteration. The functions appended return void. So when you see the value of closureArray[0]() after each iteration it would print each value of i (i.e. 1 to 5) and return void. If you see the value of closureArray[0]() after the loop has executed it would return 5 and void. Moreover, for an array index, it would return the same value.

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.