nRewik
nRewik

Reputation: 9148

How Swift captures mutable and immutable struct

I'm confused about how Swift captures mutable and immutable struct

My code downloads images asynchronously, and after the download finish, the completion closure will be called.

In the following code, It prints captured index value. The first code will print only 17. But the second code will print 0 1 2 ... 16. ( sponsorClass.count == 17 )


The firs code is

var index = 0
for sponsor in sponsorClass{
    var image = AsynchronousLoadImage( sponsor.imageURL ){ loadedImage in
        println("\(index)") //print 17
    }
    index++
}

and the second code is

var index = 0
for sponsor in sponsorClass{
    let tempIndex = index
    var image = AsynchronousLoadImage( sponsor.imageURL ){ loadedImage in
        println("\(tempIndex)") //print 0,1,2,..,16
    }
    index++
}

Upvotes: 1

Views: 2002

Answers (2)

F_Boris
F_Boris

Reputation: 170

Simply put:

Let = immutable var (constant) - value CAN'T be changed.

Var = mutable ( variable) - value CAN be changed.

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385610

You must think of a var or let statement as creating a variable (or constant) when the statement is executed in order to understand what's going on. The statement creates a new variable (or constant) each time it's executed.

In your first example, you create a variable named index once, before the loop starts. Each closure (you create 17 of them) “closes over” that same index variable. This means that each closure shares the index variable with the outer scope (the block that defines index) and all the other closures. There's only one “copy” of index, so when you modify it in your loop, each closure sees the modification (when the closure eventually runs).

In your second example, you create a new variable named tempIndex on each loop iteration. These 17 variables are independent of each other. Each closure closes over the variable that was created in the same loop iteration as the closure. That is, the closure created while index == 0 closes over the tempIndex that was also created while index == 0, and the closure created while index == 1 closes over the tempIndex that was created while index == 1, and so on. Thus you create 17 independent variables (each named tempIndex), and 17 closures, and each closure closes over a separate variable. Since you never modify any of the 17 tempIndex variables after you create them, each closure sees the original value assigned to its corresponding variable.

Upvotes: 1

Related Questions