Swift Closures: @escaping Explained

Sean Allen
28 Jun 202004:44

Summary

TLDRThis video delves into Swift's escaping and non-escaping closures, focusing on their practical differences and usage scenarios. Sponsored by DevMountain, a boot camp for coding and design, the presenter uses a network call example to illustrate the necessity of an escaping closure when the function's execution extends beyond its scope, such as waiting for a network response. The video also touches on the importance of avoiding retain cycles when using escaping closures, providing a clear explanation of when and why to use each type of closure in Swift.

Takeaways

  • 😀 The video discusses the concept of escaping and non-escaping closures in Swift and their practical applications.
  • 🏫 The video is sponsored by DevMountain, a coding and design boot camp offering various programs including iOS development.
  • 🎓 The presenter is a boot camp graduate and has been an iOS developer for five years, providing credibility to the discussion.
  • 🔗 DevMountain offers career services and financing options, and they are interested in feedback from the presenter's viewers.
  • 📞 The 'escaping' keyword in Swift is used in the context of closures that need to outlive the function they are passed to, such as in network calls.
  • 🌐 The example given is a network call to a GitHub API to fetch a list of followers, which is a common scenario for using escaping closures.
  • 🕊️ Non-escaping closures are executed immediately within the scope of the function they are defined in, without needing to 'escape'.
  • ⏱️ Escaping closures are used when a task, like a network call, takes time to complete and the closure needs to wait for the result.
  • 🔄 The presenter mentions automatic reference counting in Swift, which is crucial for understanding how escaping closures work in memory.
  • 🔄 The video touches on the importance of avoiding retain cycles when using escaping closures, as they maintain a reference to the function's context.
  • 👨‍🏫 The presenter offers to create courses and invites viewers to check out their site for more educational content.

Q & A

  • What is the main topic of the video?

    -The main topic of the video is about explaining the concept of escaping and non-escaping closures in Swift.

  • What does the term 'escaping' refer to in the context of closures in Swift?

    -In the context of closures in Swift, 'escaping' refers to a closure that needs to outlive the function it is passed to, often because it is used asynchronously, such as in a network call.

  • Why is the 'escaping' keyword used in the 'get followers' function example?

    -The 'escaping' keyword is used in the 'get followers' function example because the closure needs to execute after the function has completed, specifically after a network call has returned its data.

  • What is the difference between escaping and non-escaping closures?

    -Escaping closures are those that need to outlive the function they are passed to, often due to asynchronous execution. Non-escaping closures, on the other hand, are executed immediately within the scope of the function they are passed to.

  • What is the common scenario presented in the video where an escaping closure is used?

    -The common scenario presented in the video where an escaping closure is used is making a network call, such as fetching a list of followers from an API.

  • Why is it important to understand the difference between escaping and non-escaping closures?

    -Understanding the difference between escaping and non-escaping closures is important to manage memory correctly and avoid retain cycles, especially when closures are used in asynchronous tasks.

  • What is the role of the 'self' reference in the context of escaping closures?

    -In the context of escaping closures, the 'self' reference is used to prevent retain cycles and to ensure that the closure has access to the instance of the class or struct it was created in, as it may outlive the original function's execution.

  • What is the sponsor of the video mentioned in the script?

    -The sponsor of the video is DevMountain, an in-person coding and design boot camp that offers housing at no extra cost for full-time immersive students.

  • What additional services does DevMountain offer besides their iOS development program?

    -DevMountain offers additional services such as programs in web development, software QA, and UX design, as well as a career services team to help with job placement and financing options.

  • What is the significance of the 'weak self' capture list in the context of the script?

    -The 'weak self' capture list is used to prevent strong reference cycles in closures that capture 'self'. It ensures that the closure does not inadvertently keep a strong reference to the instance it is part of, thus avoiding memory leaks.

  • How does the video help the viewer understand the practical application of escaping closures?

    -The video helps the viewer understand the practical application of escaping closures by demonstrating a real-world example of making a network call to fetch data and then using the closure to update the UI once the data is received.

Outlines

00:00

📚 Introduction to Escaping and Non-Escaping Closures in Swift

The video begins with an introduction to the topic of escaping and non-escaping closures in Swift programming language. The presenter explains the difference between the two and sets the stage for a detailed explanation. The video is sponsored by Dev Mountain, a boot camp offering various programs including iOS development, web development, software QA, and UX design. The presenter, a boot camp graduate, highlights the career services and financing options available at Dev Mountain and encourages viewers to check out the provided link for more information.

🔗 Understanding Escaping Closures with a Network Call Example

The presenter dives into the concept of escaping closures using a network call as an example. They illustrate a function named 'getFollowers' that makes an API call to retrieve a list of followers and display them in a collection view. The closure in question is marked as 'escaping' because it needs to outlive the function's execution time, waiting for the network response. The explanation clarifies that an escaping closure is used when the closure's execution extends beyond the scope of the function it's passed to, such as in the case of asynchronous operations like network calls.

🔄 The Importance of Reference Cycles in Escaping Closures

The video continues with a deeper look at the implications of using escaping closures, particularly the issue of retain cycles. The presenter explains that because the closure is executed after the function has completed, it must maintain a reference to the view controller to update the UI and perform other tasks. This leads to a discussion about 'weak self' and 'unowned self' capture lists to prevent retain cycles, which can cause memory leaks. The presenter also mentions a previous video on automatic reference counting for those unfamiliar with the concept.

Mindmap

Keywords

💡Escaping Closures

Escaping closures in Swift are closures that need to outlive the function they are passed to. In the context of the video, this is exemplified by a network call where the closure is executed after the function completes its execution, such as when the network response is received. The video script mentions tagging a closure with '@escaping' when making a network call to get a list of followers, which is a common scenario where an escaping closure is necessary.

💡Non-Escaping Closures

Non-escaping closures are those that are executed within the scope of the function they are passed to and do not need to outlive the function's execution. The video script contrasts escaping closures with non-escaping ones, explaining that non-escaping closures are executed immediately within the function's scope, which is beneficial when the task can be completed within that context without needing to retain state or perform asynchronous operations.

💡Swift

Swift is a powerful and intuitive programming language developed by Apple for iOS, macOS, watchOS, and tvOS app development. The video script discusses Swift's closure feature, which is a self-contained block of functionality that can be passed around and used in the code. Swift's handling of closures, including the concepts of escaping and non-escaping, is central to the video's theme of asynchronous programming.

💡Network Call

A network call is a request made to a server or an API to retrieve or send data over a network. In the video script, a network call is used as a practical example to illustrate the use of escaping closures. The script describes a scenario where the 'get followers' function makes a network call to the GitHub API to retrieve a list of followers, necessitating the use of an escaping closure to handle the response asynchronously.

💡API

API stands for Application Programming Interface, which is a set of rules and protocols for building software applications. The video script specifically mentions the GitHub API, which is used to make a network call to retrieve a list of followers. APIs are integral to modern software development, allowing different software systems to communicate and exchange data.

💡CollectionView

A collection view in iOS development is a powerful and flexible user interface component that can display a grid or list of items. In the video script, the closure's result from the network call is used to populate a collection view with a list of followers. This demonstrates how closures can be used to update the UI based on asynchronous operations like network calls.

💡Automatic Reference Counting (ARC)

Automatic Reference Counting is a feature in Swift that manages the memory of objects by keeping track of the number of references to each object. The video script mentions ARC in the context of escaping closures, explaining that because closures are reference types, ARC increments the reference count when a closure outlives the function that created it, which is a common scenario with escaping closures.

💡Retain Cycle

A retain cycle occurs in programming when two or more objects互相引用 each other, causing them to never be deallocated because their reference counts never reach zero. The video script warns about the potential for retain cycles when using escaping closures, as these closures often need to capture and reference the context in which they were created, which can inadvertently create a cycle if not handled correctly.

💡DevMountain

DevMountain is an in-person coding and design boot camp mentioned in the video script as the sponsor of the video. It offers programs in iOS development, web development, software QA, and UX design, along with career services and financing options. The script highlights the speaker's personal experience as a boot camp graduate, emphasizing the role such programs can play in launching a career in software development.

💡Career Services

Career services are programs and resources provided to help individuals find employment, develop career plans, and improve job search strategies. In the video script, DevMountain's career services team is highlighted as a resource for students to assist with job placement, which is an important aspect of educational programs that prepare students for the professional world.

💡Financing Options

Financing options refer to the various methods and plans available for individuals to pay for educational programs or services. The video script mentions that financing options are available for students at DevMountain, which is crucial information for potential students who may require financial assistance to participate in the boot camp programs.

Highlights

Today's video discusses escaping and non-escaping closures in Swift.

The video is sponsored by DevMountain, a coding and design boot camp offering housing and career services.

The presenter is a boot camp graduate and has been an iOS developer for five years.

DevMountain offers programs in web development, software QA, and UX design, in addition to iOS development.

The presenter uses a network call example to explain the use of 'escaping' closures in Swift.

A closure is marked as 'escaping' when it needs to outlive the function it is passed to.

The 'escaping' keyword is explained in the context of an API call to retrieve a list of followers.

Closures can either execute immediately within the function's scope (non-escaping) or after the function has completed (escaping).

The presenter emphasizes the importance of understanding the scope and lifetime of closures in Swift.

The video provides a practical demonstration of a network call and how it relates to escaping closures.

The concept of 'escaping the lifetime of the function' is discussed in detail.

The presenter explains the use of 'weak self' to prevent retain cycles when using escaping closures.

The video clarifies the difference between escaping and non-escaping closures with a real-world coding example.

The importance of managing memory and references when working with closures is highlighted.

The presenter provides a summary of when to use 'escaping' and when to use 'non-escaping' closures.

The video concludes with a call to action for viewers interested in learning more about iOS development.

The presenter invites viewers to check out their own courses for further learning.

Transcripts

play00:00

today we're talking about escaping

play00:01

closures in Swift we're gonna talk about

play00:04

the difference between non escaping and

play00:05

escaping what that actually means and

play00:08

when to use it but first today's video

play00:11

was sponsored by Devon mountain dev

play00:13

mountain is an in-person coding and

play00:15

design boot camp that offers housing at

play00:17

no extra cost for full-time immersive

play00:19

students now if you know my story I

play00:21

myself am a boot camp grad it was part

play00:23

of the process to help launch my iOS

play00:25

developer career which I'm going on year

play00:27

five now in this wonderful profession

play00:29

but aside from their iOS development

play00:31

program dev Mountain also offers

play00:33

programs in web development software QA

play00:35

and UX design they even have a career

play00:37

services team to help you with job

play00:39

placement and financing options are

play00:41

available in dev Mountain loves hearing

play00:43

from my viewers so if you or someone you

play00:44

know is ready to start this journey into

play00:46

iOS development be sure to check out the

play00:48

link in the description all right back

play00:50

to the video so I'm gonna use a very

play00:52

common circumstance on when you would

play00:54

use at escaping to explain this and that

play00:57

is a network call here you can see this

play00:59

function get followers real quick let me

play01:02

show you what's actually going on on the

play01:03

screen because I'd like to give the

play01:04

context here we are hitting the get up

play01:06

API we're getting a list of followers

play01:08

and we're showing it in this collection

play01:10

view and I don't know I always like to

play01:11

show that stuff because just looking at

play01:13

code I like to see the context of what

play01:14

the code is actually doing helps me

play01:16

understand what's going on so there you

play01:18

go that's what's going on so about this

play01:19

escaping keyword here that you see so as

play01:23

you can see we have function get

play01:24

followers we pass in a username page

play01:25

whatever but here's our closure right

play01:28

and it returns a result that has an

play01:30

array of followers or an error right

play01:32

this is how we populate our collection

play01:34

view well we tagged this closure at

play01:36

escaping now why did we do that well

play01:39

when you pass in a closure as a

play01:41

parameter and a function which is what

play01:43

we're doing right we have a parameter

play01:44

called completed and here's our closure

play01:46

it has it can do one of two things it

play01:49

can be executed like immediately within

play01:51

the scope of this function which you

play01:53

know to refresh you the scope is this

play01:54

curly brace down to this curly brace

play01:57

which is basically everything that's

play01:58

happening and get followers so one

play02:00

option is to have that closure execute

play02:02

immediately within the scope of that

play02:03

function that would be non escaping

play02:06

right because it doesn't have to escape

play02:07

so think about the word escape I just

play02:09

said it five straight times

play02:11

it's basically escaping the life

play02:13

time of this function so what that means

play02:16

is is this closure needs to you'll often

play02:18

hear it called use at escaping if the

play02:21

closure has to outlive the life of the

play02:23

function so when this function get

play02:25

followers gets called all this code

play02:27

executes however what this code is

play02:30

executing on is this is making a network

play02:32

call this is why this is a common

play02:33

example so when you make a network call

play02:35

right we requested the github API hey

play02:38

give me the list of followers and then

play02:39

we download that list right that takes

play02:41

time if you're on good Wi-Fi may take

play02:44

half a second if you're on bad cellular

play02:46

service that could take seven seconds

play02:48

right so our closure which is what we

play02:51

call to execute you know once we get our

play02:53

list back that's how we populate our

play02:54

collection view our closure needs to

play02:56

outlive the life of this function

play02:58

because it's sitting around like waiting

play03:00

for the network call to come back and

play03:02

while it's out there waiting for the

play03:04

network called to come back right it's

play03:06

got to live somewhere and it so it lives

play03:08

in memory so because closures are

play03:10

reference types so what that means is

play03:12

there some automatic reference counting

play03:13

going on and because it's out there

play03:15

living in memory that reference count

play03:17

has been incremented to one side note if

play03:19

you're not familiar with automatic

play03:20

reference counting I did a video all

play03:22

about that I'll put the link in the

play03:23

description so if we go to where get

play03:25

followers here is called on the follower

play03:27

list VC you'll see Network managers not

play03:29

shared get followers you'll see we have

play03:31

the we called it result that's what our

play03:33

closures you know coming back as and you

play03:35

can see we're using the week self

play03:36

capture list that is to you know prevent

play03:38

some retain cycles but back to the

play03:40

closure kind of living by itself in

play03:41

memory write it it outlived the life of

play03:44

its original function that is why it

play03:45

needs to have a reference to self to do

play03:48

all this you know dismiss loading view

play03:49

update UI etc so you know it has its own

play03:53

reference to this view Co self being

play03:54

this view controller earth to follower

play03:55

list VC so that's something you need to

play03:57

keep in mind and be careful of the

play03:59

retain cycle aspect of things when using

play04:02

these escaping closures because again

play04:03

they're out there living in memory by

play04:04

themselves so they have to have

play04:06

references to you know whatever they're

play04:07

using so back to the network manager

play04:09

again the summary when you use add

play04:10

escaping is when the closure needs to

play04:13

outlive the life of the function that

play04:15

it's a part of and like I just showed

play04:17

you a super common example of that is

play04:19

doing networking so hopefully this video

play04:21

helped clear up escaping vs. non

play04:23

escaping remember non escaping is it'll

play04:25

execute like a meet

play04:27

within the scope hopefully I cleared all

play04:29

that up if you enjoyed my teaching style

play04:30

my presentation I check out the site on

play04:33

the screen I started creating my own

play04:34

courses we'll talk to you the next video

Rate This

5.0 / 5 (0 votes)

Related Tags
SwiftClosuresEscapingNon-EscapingiOS DevelopmentNetwork CallsAPICoding BootcampDev MountainARCRetain Cycles