Capture Lists in Swift
Image via Author

Capture Lists in Swift

This article is written with the assumption that you have some basic familiarity with the concept of capturing values. If you’re not completely clear on the subject, you should refresh your knowledge by reading my article on Closures, Nested Functions and Capturing Values in Swift.


Making sense of it all

In Swift, there is a way for a function to refer to a variable outside of itself, and acquire the value but not capture the variable. However, this is only possible with an anonymous function.

The syntax is straightforward. After the opening curly brace, place the variable or comma-separated list of variables inside of square brackets, followed by the keyword in.

If there is an in keyword already in the function, then you precede the parameter names with the capture list.

Ok, let’s see it in action.


Capture Lists in Swift



var valueOne = 1

var valueTwo = 2

let captureClosure: () -> () = { [valueOne, valueTwo] in
    
    print(valueOne, valueTwo)
}

captureClosure()

valueOne = 100

valueTwo = 200

captureClosure()

// 1 2
// 1 2
        

Variables valueOne and valueTwo are declared outside of captureClosure. The first time captureClosure is called, it prints out the values 1 and 2.

Then the variables are changed to 100 and 200 respectively before calling captureClosure again. The values printed remain the same because captureClosure had already captured the values of 1 and 2 at the time it was declared.

The effect of such an operation is that the variables operate as if they had been passed into the function as parameters rather than a closure capture. This is why they can’t be modified. They are essentially treated as constants.

If you’re unsure why global variables in Swift can’t be modified inside functions, read my article on In-Out Parameters in Swift.

Capture lists are a powerful feature in Swift because they ensure your closures behave as expected without causing unintended side effects like memory leaks.

要查看或添加评论,请登录

Ijeoma Nelson的更多文章

社区洞察

其他会员也浏览了