How Do You Write Closures in Swift?

  Переглядів 112,896

Lets Build That App

Lets Build That App

6 років тому

Closures are used everywhere in Swift and the UIKit APIs that we have access to. Today we'll go through a simple exercise of how to write and apply closures by going through a simple algorithm exercise. This lesson covers how to write filtering functions using closures to make our programs more robust. Have fun.
Instagram Firebase Course
www.letsbuildthatapp.com/cour...
Facebook Group
/ 1240636442694543
iOS Basic Training Course
www.letsbuildthatapp.com/basi...
Completed Source Code
www.letsbuildthatapp.com/cour...
Follow me on Twitter: / buildthatapp

КОМЕНТАРІ: 180
@antonlebedev2890
@antonlebedev2890 9 місяців тому
Now I seem to be getting pretty much closer to the point of understanding WHY do we need closures)) Thanks a lot!
@generalk9947
@generalk9947 6 років тому
I am starting university in a couple weeks and by previously watching ur top quality videos on software engineering u have really inspired me to take this course even more because I now realise the many things you can do as a software engineer especially creating apps and how much you can potentially earn thanks👌🏾
@developerios6096
@developerios6096 6 років тому
I love these kind of videos, where you explore the code syntax for advanced stuff. Nice and clean, thank you brian!
@PedrocaRicardo
@PedrocaRicardo 6 років тому
FINALLY someone who made me understand closures, thank you!
@kennram-code2941
@kennram-code2941 2 роки тому
totally agree - was completely lost until I saw this vid.
@israman30
@israman30 6 років тому
Beautiful closure explanation..!! Thank you!
@mutasemwahbeh6954
@mutasemwahbeh6954 3 роки тому
Eventually someone decided to make closure understandable and easy to use thank you sir !
@emindeniz
@emindeniz 5 років тому
Best tutorial for Closures so far. Thank you man.
@liminal18
@liminal18 6 років тому
Thanks paused the video and used a closure to solve some mases in that ios swift game. Was a lot of fun.
@Pedruchito
@Pedruchito 4 роки тому
Thank you very much for making this tutorial video and, for making it with simple explanations so I can understand it. I love it !!
@jonaseduardo01
@jonaseduardo01 4 роки тому
Nice explanation , I've been watching tutorials about this in the last days , I thinks that is a very useful concept
@rohanghorpade2894
@rohanghorpade2894 4 роки тому
Best tutorial on closures !!!! I want to learn more about @escaping closures.
@drewster6981
@drewster6981 6 років тому
Brilliant. Really good explanation of closures.
@markdang3379
@markdang3379 6 років тому
Your videos are so helpful. Very clear and informative. Thank you!!!
@andreasbagias4334
@andreasbagias4334 6 років тому
Hello. Interesting video. I have never used closures like that. Mostly for async tasks so far. Will try to integrate a few of your examples in my future projects. Cheers.
@marie-pascalechauvel9169
@marie-pascalechauvel9169 5 років тому
This video is so helpful. Thanks for posting it!
@zarioiubogdan1164
@zarioiubogdan1164 6 років тому
This was really helpful. Thank you!
@BreatheDigital
@BreatheDigital 6 років тому
Really needed this! Many thanks! You have yourself a new subscriber.
@Noahnrg22
@Noahnrg22 6 років тому
Another great video, everyday you surprise me with what I can learn, thanks !!
@stevengao8345
@stevengao8345 6 років тому
nicely explained, can't wait for you to talk about Generics in the future : )
@andresraigoza2082
@andresraigoza2082 2 роки тому
You are a great teacher. Thank you
@septronic2010
@septronic2010 6 років тому
Another really useful tutorial! Thanks a lot
@jonas14812
@jonas14812 4 роки тому
Very clear and informative, thank you! 😇
@weitang9727
@weitang9727 6 років тому
Great tutorial, thank you Brian
@kaistasch4028
@kaistasch4028 6 років тому
Thanks a lot Brian!
@RM-di6oe
@RM-di6oe 5 років тому
Sir its awesome thanks for your contribution for making our future bright...
@amizan8653
@amizan8653 6 років тому
Great video, thanks for posting!
@supriyajagtap4050
@supriyajagtap4050 3 роки тому
Nicely explained 🤩, thank you
@maxgebhardt6213
@maxgebhardt6213 3 роки тому
One of my favorite youtubers! Awesome stuff!
@caragold9329
@caragold9329 4 роки тому
Thank you! It was extremely helpful))
@manickamt127
@manickamt127 3 роки тому
This was wonderful explanation. I’ll use my code with closure an upcoming days 🙂🙂
@KouroshPiano
@KouroshPiano 6 років тому
Great video. Keep it up Brian ✌🏼
@DrZiggyzoo1
@DrZiggyzoo1 6 років тому
6:54 "You probably don't want to name your functions as long as this." I would disagree with that to an extent. You can either have a vague function name and comments, which will more than likely not get updated if someone changes the code. Or you can have a longer, but more meaningful function name that actually explains what is happening. A good example of this is a guy I used to work with. He hates how comments always become out of date and doesn't use them too much. So instead, he uses longer, but more meaningful function names. We once made fun of him because he had a function name that was close to twice as long as filterWithPredicateCondition(). But on the flip side, everyone who looked at the function knew it's exact purpose.
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
True, I'm also in the camp for longer function names as long as it makes grammatical sense.
@bureaucraticfelcher8357
@bureaucraticfelcher8357 4 роки тому
Agree, self documenting code is better than commenting document/explanation.
@AudriezWorld
@AudriezWorld 4 роки тому
Thanks man. Very helpful
@Vankien96
@Vankien96 6 років тому
Thanks so much .helpful tutorial
@sampep
@sampep 3 роки тому
Amazing! Big thanks!
@kaiseration
@kaiseration 5 років тому
I just tested this code: func filterWithPredicateClosure(closure: (Int) -> Bool, numbers: [Int]) -> [Int]{ let greater = numbers.filter(closure) return greater } filterWithPredicateClosure(closure: { return $0 > 6 }, numbers: [1,2,3,4,5,10]) It successfully run. :D Thanks Brian.
@vbuddy8
@vbuddy8 4 роки тому
Love your videos! Been helping me so so much. I don't like how you panned the audio though (: Still thumbs up for being so awesome
@albaqawi
@albaqawi 6 років тому
Hi Brian, great video! how about a follow up with closures that contain important keywords like @escaping in Swift?
@lostintheheatofitall
@lostintheheatofitall 5 років тому
please
@ashleighgray4291
@ashleighgray4291 6 років тому
THE NEW UKposts UPDATE IS AMAZING!!!!
@shayan_ecksdee
@shayan_ecksdee 6 років тому
Hunter Gray are you using phone or pc
@HairyPixels
@HairyPixels 6 років тому
Yet another pointless changes I need to learn.
@albaqawi
@albaqawi 6 років тому
I agree outstanding material design layout! finally they used it
@nhantrivinh
@nhantrivinh 6 років тому
Great video Brian as always! Thank you for videos they are really awesome! At the moment I am very curious about how to handle uploading multiple images. I think this will be a great topic. Please let me know your thoughts!
@alekseidanilov9279
@alekseidanilov9279 6 років тому
very cool lesson, thank you!!!
@arrinal
@arrinal 2 роки тому
Bro... you save me from understanding closure! Thanks a lot!
@lifestoriesbook4723
@lifestoriesbook4723 5 років тому
One of the best videos of using closures in a simple way.Great One Thanks.But do you know any source for going in depth.
@---ml4jd
@---ml4jd 4 роки тому
nice work with the audio, real pro level stuff.
@moenaim8672
@moenaim8672 4 роки тому
too much thanks for you'r hard work
@-kkkirito5658
@-kkkirito5658 5 років тому
Hi Brian, really need a lesson of weak self and strong self in swift and how to avoid the memory leak in closures. Many thanks!
@sashamakedonskii
@sashamakedonskii 6 років тому
Hi brian! Nice explanation of closures! It will be nice to see the `Generics` tutorial. Thanks
@huqiao
@huqiao 6 років тому
Totally agree, a tutorial on generics would be wonderful !
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
+Qiao Hu I believe the lessons on stacks and generics shows you how to use em
@Quant15
@Quant15 6 років тому
Hi Brian! Thanks for explanation. One more question - what about unwoned and weak references -> do we need to use them in every closure?
@codinggyaan2570
@codinggyaan2570 3 роки тому
Nicely Explained
@Cdswjp
@Cdswjp 6 років тому
You’re the man brother
@midnytromeo
@midnytromeo 6 років тому
You're a inspiration.
@SevenDeMagnus
@SevenDeMagnus 6 років тому
Hi. Thanks Brian and Apple for creating closures. It's less typing when you need to modify some logic. The closure within a closure is like a dream within a dream within a dream- Inception movie:-) God bless Proverbs 31
@longh
@longh 2 роки тому
Thanks a lot!
@shuks1337
@shuks1337 3 роки тому
you saved me, thanks a lot
@SevenDeMagnus
@SevenDeMagnus 4 роки тому
Cool, thanks.
@SalesforceMiind
@SalesforceMiind 5 років тому
nicely explained
@avisekhon5915
@avisekhon5915 6 років тому
Hi Brian, great video. However I think you should have mentioned trailing closures too, as it simplifies the code quite a bit. func greaterThanPredicateClosure(numbers: [Int], closure: (Int) -> Bool) -> [Int]{ // body } let result = greaterThanPredicateClosure([1, 2, 3, 4, 5], { value in return value > 5 }) Here, we use the weird closure as parameter syntax. let result = greaterThanPredicateClosure([1, 2, 3, 4, 5]){ value in return value > 5 } Here, we use the trailing closure syntax, where if a closure is the last parameter of a function, it can be written outside the function parenthesis, making it easier to read. Other than that, I liked the video.
@diegogarciar
@diegogarciar 6 років тому
you can even reduce it to {$0>5}
@avisekhon5915
@avisekhon5915 6 років тому
Yes, I didn't mention that because it'd be confusing for beginners. I believe only the first two parameters get values like that ($0 and $1) or does it extend to the number of parameters the closure has ($0...$n)?
@moussahaidous6872
@moussahaidous6872 6 років тому
i believe it does expand to $n
@dacypher22
@dacypher22 5 років тому
Avi Sekhon Ahhh. I am a professional programmer but am just trying to learn Swift and iOS development for the first time. I was trying to fill out an autocompleted method call and XCode kept switching it to this format and I was so confused. That is really some weird syntax for someone coming from JS, Java, C#, etc.
@brod515
@brod515 5 років тому
I really don't think that's easier to read ; I truly believe that's far more confusing to read
@laiqueahmed6613
@laiqueahmed6613 6 років тому
nice video . Thanx!!
@annaxia3237
@annaxia3237 3 роки тому
Thanks!!!
@akashskumar6389
@akashskumar6389 Рік тому
finally understood closures:)
@stanymiles
@stanymiles 6 років тому
This was superuseful!!!
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
Indeed, glad you enjoyed these more advanced concepts of Swift.
@HieuLe-mz2lb
@HieuLe-mz2lb 6 років тому
so cool, you are awesome !
@vigneshwaran6348
@vigneshwaran6348 3 роки тому
good explanation thanks. why are they use some times escaping key word and why we are put front of the parameter _ these symbol like _escaping
@kayeshabhi
@kayeshabhi 2 роки тому
Thank you
@vjatseslav.p.8173
@vjatseslav.p.8173 6 років тому
Hi Brian, I think it would be also nice to say about short-way syntax of closures. For example: func closureTest(closure: (Int) -> Bool, array: [Int]) -> [Int]{ return array.filter(closure) } let result1 = closureTest(closure: {(num) -> Bool in return num > 4 }, array: [1,4,5,6,7,8]) let result = closureTest(closure: {$0 > 4}, array: [1,4,5,6,7,8]) I think it's obvious, that short-way syntax much more comfortable for using in code.
@bitsurfer0101
@bitsurfer0101 3 роки тому
I don't like the short-hand method since it seems a bit lazy and harder to read. It's a nice idea though
@prahaladdemo6902
@prahaladdemo6902 6 років тому
Your video is very lenthy for downloading
@Mr_Jai_Kalra
@Mr_Jai_Kalra 5 років тому
superb
@jackshihtaken
@jackshihtaken 6 років тому
Hey great video, but doesn't Swift already have a built in collection function called Filter?
@augustogalindo8687
@augustogalindo8687 3 роки тому
I was reading the closures section in the Swift Guide in Apple Books, didn’t search anything about it but suddenly this video popped up in recommendations. I hope it is just coincidence
@martian7691
@martian7691 6 років тому
Kind of syntax used in Parse and firebase for querying I guess, also using clousures for completion handlers but with no returned values because they are async.
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
+Misael Garay yes this is pretty much how the parse and firebase completion handlers are written. Hope you can use this knowledge in your own apps
@bitsurfer0101
@bitsurfer0101 3 роки тому
If you are appending the filtered values to the array, do you need to clear out the array every time you call the function?
@shubhambairagi4942
@shubhambairagi4942 5 років тому
Hey Brian, I follow your videos to make my code robust and reach to standard. Can you please make a video to clarify the difference between Array and Set.
@LetsBuildThatApp
@LetsBuildThatApp 5 років тому
A set is a collection of items without ordering, whereas an array is sequenced.
@joca251078
@joca251078 6 років тому
Difficult to understand, but amazing.
@dambar011
@dambar011 2 роки тому
Great
@manickamt127
@manickamt127 3 роки тому
I need to load the chat data for tableview. I have already used fetched results controller for getting the data . 1. Let me just explain how can I load bunch of data while scrolling to top 2. While I come friend list, how much data can I load to chat page on first time
@mukulsharma150
@mukulsharma150 6 років тому
Mast YAAR
@stevengao8345
@stevengao8345 6 років тому
within closures, i see lots of time people use [weak self] to prevent retain cycle, i mean how do we figure out if inside a closure there is a retain cycle ? can you explain more about it in you future tutorial ? thanks very much
@marcaupont9145
@marcaupont9145 6 років тому
Awesome awesome vid!!!!
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
You're awesome too Marc!
@richardwalters9249
@richardwalters9249 3 роки тому
Trying to identify key components of closures: (a) the struct/func/etc. that defines the closure signature will also be the caller the closure; (b) the closure definer (or where the closure body is implemented) is where the exact VALUES for the parameters are located. This guy MUST match the defined signature, but he gets to define the implementation of the closure against the values in his scope.
@bs5920
@bs5920 6 років тому
Hey Brian! Thanks for the video. I am new to Swift and the concept of closures and I have a question. Wouldn't it be more sensible to create an extension on Array for this purpose? Something like: extension Array { func filterList(_ isIncluded: (Element) -> Bool) -> [Element] { var result = [Element]() for x in self where isIncluded(x) { result.append(x) } return result } } So you could call it via dot notation on your Array: let filteredList = [1, 2, 3, 4, 5, 6, 7, 8].filterList { $0 > 3 } Thanks in advance!
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
As you might or might not know already, Swift already comes with the filter function out of the box for arrays. The idea of closures applies to a much broader and generic programming paradigm. Today's lesson was simply an introduction on how to write out the syntax.
@bs5920
@bs5920 6 років тому
Lets Build That App Thank you very much! As I'm pretty new to programming, with Swift being my first programming language (actually studying life sciences), I'm learning tons of new stuff every day and your videos help me out a lot.
@bitsurfer0101
@bitsurfer0101 3 роки тому
@@LetsBuildThatApp How could you use the sort function if you are using a struct and are sorting one or more of the variables?
@hareeshgangadhara415
@hareeshgangadhara415 3 роки тому
You're rocking voong
@kelvinyan2709
@kelvinyan2709 6 років тому
Hi Brian, could you tell me which microphone you use?
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
+Kelvin Yan it's a rode nt1a mic
@hermankster4914
@hermankster4914 6 років тому
Love your videos! I'm currently learning Swift but lately have been hearing a lot about Progressive Web Applications and honestly a it does scare beginners like me learning IOS programming when people keep saying this might replace it. Can you do a video on it? I'm sure you've been hearing it a lot lately
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
PWA was supposed to replace native 10 years ago.....
@hermankster4914
@hermankster4914 6 років тому
I've been learning swift for about 3 months now and lately it's just been popping up on my youtube feed. It just gets a bit scary while you're learning native apps and these things keep popping up saying it'll replace native apps...
@hermankster4914
@hermankster4914 6 років тому
The most recent one is posted yesterday by CodingTech
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
You'll get used to this in software with every new framework that comes out
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
Yep and wont be the last.
@MrBlaq
@MrBlaq 6 років тому
Does Swift have anything similar to "Promises" or "async/await" in Javascript? And would it be possible to get a tutorial on the "dispatch" function in the future?
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
+MrBlaq there is a third party pod that lets you use promises
@dariuszku2687
@dariuszku2687 4 роки тому
Still helpfull Brian:)
@Traoreee
@Traoreee 6 років тому
How do you make selected codes to //comment?? What is the shortcut?
@anshuiphonedevswiftandswif2107
@anshuiphonedevswiftandswif2107 3 роки тому
Nice but still I have a doubts when we can use function and when we can use closure and completion handlers . Y we have to use those
@cuongcuong6848
@cuongcuong6848 5 років тому
please introduce some of the best free books for swift learning??
@MrSenChoi
@MrSenChoi 3 роки тому
It seems Apple releases swift book on every update. Search “the swift programming language” in bookstore in Apple Books app.
@murad3460
@murad3460 6 років тому
Will there be more project tutorials like Twitter feed in IOS?
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
+John Galew I've stopped producing the Twitter feed videos
@murad3460
@murad3460 6 років тому
Excuse my vagueness,i meant tutorials Like Twitter and Audible
@giovanniofficial1666
@giovanniofficial1666 4 роки тому
Hi I would like to know if you do you're video from taiwan or somewhere else I can see in most video in background taiwan picture
@LetsBuildThatApp
@LetsBuildThatApp 4 роки тому
Vacation videos from taiwan
@giovanniofficial1666
@giovanniofficial1666 4 роки тому
@@LetsBuildThatApp amazing if you pass by again let me know I invited you for a drink. I'm in Taipei city, An icon of swift like you that's insane. ;)
@usgqgwa
@usgqgwa 6 років тому
I have always wanted to see how the guys behind radio mic look when they speak like this. Now I know :)
@cxn_media
@cxn_media 4 роки тому
I think you should use white background and black text in editor for better visual.
@LetsBuildThatApp
@LetsBuildThatApp 4 роки тому
If you're 40+ then you use white background, everyone else uses black now.
@irynasherepot9882
@irynasherepot9882 3 роки тому
Is my internet slow or the video is blurry? Tried in different browsers
@Gojam12
@Gojam12 6 років тому
When I enter this into playground and do what you did press the run button I only get the response ready at the top and no results, this is exactly how I run ios apps is there something different going on in playgrounds?
@Gojam12
@Gojam12 6 років тому
Never mind see it
@CardinalHijack
@CardinalHijack 6 років тому
Are you back in the States Brian?
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
Yeah, back in the States again and hopefully no more traveling.
@CardinalHijack
@CardinalHijack 6 років тому
sweet. great vid btw, very well explained.
@VasaMusic438
@VasaMusic438 4 роки тому
closures complicate very much for few advantages is it right?
@gjermundification
@gjermundification 6 років тому
6:02 There is no Editor -> Refactor -> Rename ... in playgrounds?
@waltersumofan
@waltersumofan 6 років тому
If the array is left as [10,5,1,2,0] you get from the modulus [10,5,0] rather than the expected [10,5]. Can you explain that and what to do to weed it out? I understand the modulus but how to return it without the zero? Thanks
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
0 is divisible by 5 no?
@waltersumofan
@waltersumofan 6 років тому
As I said, I understand the modulus. Any value divided into zero produces zero which makes the value true so it adds it to the array. I'm asking how to produce [10,5] and avoid the [10,5,0] result. Cheers.
@waltersumofan
@waltersumofan 6 років тому
Would I just test if value != 0 but where to put it? How to skip 0 or how to ignore it?
@LetsBuildThatApp
@LetsBuildThatApp 6 років тому
+waltersumofan yeah your filter function would check for AND not equal zero
@waltersumofan
@waltersumofan 6 років тому
Thanks
@lostintheheatofitall
@lostintheheatofitall 5 років тому
Why do you have to end the variable "filteredSetOfNumbers" with () ?
@LetsBuildThatApp
@LetsBuildThatApp 5 років тому
This is how we use closures.
@prasenjitgiri919
@prasenjitgiri919 6 років тому
This is very informative but if you are still having some time to build a full fledged application for youtube - I have one request. Please make a tutorial on streaming remote audio like from Soundlcoud for a full fledged music player. Neither Apple, nor a single tutorial is out there that showcases how to build a music player. For eg. AVAudioQueuePlayer wont go reverese as its a queue. If you use AVPlayer - music wont play when in background if you handle a custom AVPlayerItem Queue. MediaITems don't work with Soundcloud stream URL's as it cannot fetch title/artist etc. There are so many problems that I cannot even begin to comprehend. Thank you for reading.
My First Take Home Interview Exercise: Flattening Nested Arrays using Recursion
18:32
Weak and Unowned Self Closure Memory Leak Fixes
12:21
Lets Build That App
Переглядів 55 тис.
ЧТО ДЕЛАТЬ, ЕСЛИ НЕ ХВАТАЕТ ДЕНЕГ НА ВОССТАНОВЛЕНИЕ ТАЧКИ?
47:52
Swift Closures Explained
14:23
Sean Allen
Переглядів 56 тис.
What is Unit Testing, Why We Use It, and Sample Test Cases
12:17
Lets Build That App
Переглядів 305 тис.
Swift 4: Introduction to Auto Layout Programmatically (Ep 1)
23:37
Lets Build That App
Переглядів 183 тис.
Swift for Beginners Part 13 - Closures
12:42
iOS Academy
Переглядів 31 тис.
How to create and use closures - Swift for Complete Beginners
18:39
Paul Hudson
Переглядів 22 тис.
Swift Closures Explained - The ONLY video you'll ever need!
17:33
Get Swifty
Переглядів 3,7 тис.
When to Semaphore vs Dispatch Group! Careful Multithreaded Shared Resource
11:11
Lets Build That App
Переглядів 45 тис.
How to use escaping closures in Swift | Continued Learning #20
21:56
Swiftful Thinking
Переглядів 17 тис.
Top 5 Programming Languages in 2022 to Get a Job
8:41
Aaron Jack
Переглядів 746 тис.
How to write Kickass Animated Circle Progress Bar (Ep 1)
14:43
Lets Build That App
Переглядів 124 тис.
ЧТО ДЕЛАТЬ, ЕСЛИ НЕ ХВАТАЕТ ДЕНЕГ НА ВОССТАНОВЛЕНИЕ ТАЧКИ?
47:52