How to create and use closures - Swift for Complete Beginners

  Рет қаралды 24,048

Paul Hudson

Paul Hudson

2 жыл бұрын

Other videos in the Closures section:
1. How to create and use closures: This video
2. How to use trailing closures and shorthand syntax: • How to use trailing cl...
3. How to accept functions as parameters: • How to accept function...
4. Summary: Closures: • Summary: Closures - Sw...
5. Checkpoint 5: • Checkpoint 5 - Swift f...
You can find the full set of videos, along with transcriptions, challenges, tests, and more, in my free 100 Days of SwiftUI course: www.hackingwithswift.com/100/...
Watch the full Swift for Complete Beginners playlist here: • Swift for Complete Beg...

Пікірлер: 71
@AnotherCG
@AnotherCG 4 ай бұрын
What I like most about these tutorials you make is you keep the font large something a lot of tutorial makers refused to understand
@tigran.zakaryan
@tigran.zakaryan Жыл бұрын
I still can't understand how the captainFirstSorted function is working. what is the logic of that function?
@thefelix1100
@thefelix1100 8 ай бұрын
For everyone that does not understand don´t worry, it is just that you need a bit of computer science basic knowledge. (I highly recommend to take an entry level University Grade CS course like harvards CS50, which is free) the sorted() function in swift basically goes through the array always just comparing two names with each other, putting the one which is alphatecial first in front until the whole array is sorted. The function does that by checking if name1 is less than name2 (in terms of alphabetical order) if that comparison returns back a true means nothing has to be done, as the first name is already in front and alphabetical lower. If the comparison returns a false the function will switch the position of the two names. The closure here just tells the sorted() function to do exactly that EXCEPT if one of the two names that gets compared is Suzanne. So if Suzanne is standing in front of the other name (which means name 1 == Suzanne) return true so it stays in front, if Suzanne is not in first order, then return false and switch Suzanne in front. If Suzanne is not in the comparison, just do the regular name1 < name2 check. I feel like Paul should have mentioned that, for absolute beginner programmers without any CS background. Hope that helps!
@namangatpalli4170
@namangatpalli4170 7 ай бұрын
Thank you sir, that's the only thing I was struggling with!
@monogidrat
@monogidrat 2 ай бұрын
Thanks a lot, that was very helpful!
@iraklyoda4213
@iraklyoda4213 Ай бұрын
Thanks man. I got exactly the same feeling that Paul was not mentioning something regarding how sorted function worked.
@chris_tteg
@chris_tteg 9 күн бұрын
Thank you very much for the clarification man. I was wondering if the parameter names "name1" and "name2" matter. Does the function sorted go through the array in the order that it was written in and then assign both name to a parameter to check which one is the greatest? Or is it the order of the parameter that important
@benjaminanic7899
@benjaminanic7899 10 ай бұрын
I was confused how name1 < name2 in the function logic accounted for all the names in the array, but it doesn’t! The logic behind the scenes of the sort() function tells the computer to go through the entire array of names. 13:10 Update: this explanation from ChatGPT helped a lot. **Concept of Pairwise Comparison**: Sorting algorithms, especially comparison-based ones, work by repeatedly comparing pairs of elements to determine their relative order. The exact pairs that get compared, and the sequence in which these comparisons occur, vary depending on the specific algorithm. When you provide a function that contains a > b as part of the functions logic flow to the `sort(by:)` method, it essentially acts as a "rule" or "guide" for the sorting algorithm. Every time the algorithm needs to determine the relative order of two elements, it will call this function with those two elements
@rogerrtewwr4723
@rogerrtewwr4723 Ай бұрын
one of the only good videos on closures I've found ... thank you
@NathanBudd
@NathanBudd 9 ай бұрын
A lot of this makes sense. One thing I'm struggling with, is a practical reason as to why one might want to *copy* a function at all? Why not use the original function?
@dereklei1746
@dereklei1746 2 жыл бұрын
When they say KZfaq is a good place, they're probably referring to this Channel. Thanks Paul for such an enlightening explanation.
@ericvaish
@ericvaish 2 жыл бұрын
That was such a lovely explaination. Thanks mate!
@karammelkon
@karammelkon Жыл бұрын
I just paused the video to comment on your brilliant teaching style and simple and clear explanation. Thank you so much! coming from JS, Swift seems like an exciting and beautiful language.
@all4ege
@all4ege 2 жыл бұрын
Oh my God!!! Thank for such a brilliant explanation!!!
@JozsefNyulas
@JozsefNyulas Жыл бұрын
This made things clear. many thanks!
@srome0711
@srome0711 2 жыл бұрын
Thank you for the reassurance I'm not a dumbass - I actually needed that.
@Drewbydrew
@Drewbydrew 2 жыл бұрын
Omg, I finally understand closures! Thank you Paul!
@aniltodakar6449
@aniltodakar6449 7 ай бұрын
Nice and deep explanations. Thank You.
@mauroabrantes5948
@mauroabrantes5948 2 жыл бұрын
Im killing myself trying to understand how name1 and name2 sort Suzanne to be first ... Can anyone help to explain to me ?
@Munchkin303
@Munchkin303 2 жыл бұрын
To sort an array of any length, you need to create a sorting function that describes how any two given elements of this array are related. For example, we give the function parameters "1" and "2" (in that order). If this order is correct, the function should return true, otherwise false. Now an integer array any length will be sorted in ascending order, and we just needed to determine the relations of only two elements. To move "Suzanne" to the beginning, the sorting function must return true if "Suzanne" is specified as the first parameter. So the sorting function will gradually move "Suzanne" to the beginning each time it compares it with other elements of the array.
@cirjeex6412
@cirjeex6412 Жыл бұрын
in short, if name1 is suzane, functions returns true, and if name2 is suzane, function returns false because suzane should be the first name, not second.
@GabeColors
@GabeColors Жыл бұрын
@twostraws we need an update that makes sense
@Vidadlaur
@Vidadlaur Жыл бұрын
I already died trying to understand it
@leon.dev89
@leon.dev89 10 ай бұрын
I’ve had to watch this video about 5 times now. I think I’m starting to understand Closures 😅
@arulpraveen
@arulpraveen 9 ай бұрын
I just watched it once and I'm baffled. I didnt understand anything lol. Let me try 4 more times like you.
@ilgaralizada7206
@ilgaralizada7206 2 жыл бұрын
thank you for video
@alexpascal5403
@alexpascal5403 2 жыл бұрын
Coming from Python, Java and js. I have learned to both love and still misunderstand swift’s idiosyncrasies
@jackle3002
@jackle3002 11 ай бұрын
Great video, very well explained in my opinion. I think the benefit of closures in my mind is being able to differentiate between functions which are general purpose and have utility in many places versus a very specific sort algorithm used to collect/filter just the data you want. Potentially it would have been a useful tool to sell the utility by going on to "need" a captainLastTeam object directly after this.. Would you go and define a whole new function for this sorting algorithm.. or would you tightly couple the algorithm in a compact way exactly where its required using closures. Maybe you have 10 slightly different filters you need to apply to your object one after the other... What then?
@avafreak252
@avafreak252 2 жыл бұрын
Thank you! You explain the concepts very well
@sulthankios3997
@sulthankios3997 2 жыл бұрын
Thank u
@chocomilkfps1264
@chocomilkfps1264 Жыл бұрын
I watched this and the following video 3 times and each time was left with the impression that this sorting function could only manipulate the order of the first 2 items in the array. In my opinion this lesson would benefit from a reshoot. Don’t mean to sound unappreciative, I love the content and teaching method usually, I just think this video skims certain things and really got me hung up.
@SmartMoneyCookie
@SmartMoneyCookie Жыл бұрын
I feel the same way. I still have the same impression that this sorting function could only manipulate the order of the first 2 items in the array.
@chocomilkfps1264
@chocomilkfps1264 Жыл бұрын
@@SmartMoneyCookie as best I understand it, It will look at pairs of names in the array in ascending order and compare them. To be precise, it looks at 2 names and compares them, and makes any adjustments necessary, then slides one position down so it’s now looking at a previous name and a new name and compares those… and it keeps doing this until it’s gone through the array. You can tell this is what it does because if you swap the Boolean values it will slide the specified name all the way to the end of the list instead of the beginning. I hope that makes some more sense, it is very awkward explaining through text
@martinkowollik1432
@martinkowollik1432 2 жыл бұрын
Great & very useful! Thanks!
@user-dh2qy1ic5p
@user-dh2qy1ic5p Ай бұрын
11:10 So we are passing 2 parameters to the function: name1 and name2, but how does it work correctly if we are passing a String array instead of strings?
@ejazmuneeb
@ejazmuneeb Жыл бұрын
pure gold secrets at free of cost for ios devs.
@spailsofficial
@spailsofficial Жыл бұрын
You really gotta explain why something works a certain way or else you might as well not bring it up. You skip right past what sorted(by:) actually does with the boolean value, which leaves a lot of people more confused than before, as seen in these comments.
@Jeff-zc6rr
@Jeff-zc6rr 2 ай бұрын
So it works like a java method. I don't get the significance. Are you saying the return type of a swift func is not the data type? If it returns a string it is not a string?
@YoAbaAba
@YoAbaAba 2 жыл бұрын
I love you
@BlushinGun
@BlushinGun 2 жыл бұрын
As a beginner I was confused with name1 and name2 representing all the positions in the array until I switched name1 to return false and name2 to return true. Then everything clicked in my head.
@abdou023
@abdou023 2 жыл бұрын
What do you mean? did you change the naming or specify them to return true or false?
@tigran.zakaryan
@tigran.zakaryan Жыл бұрын
I did that, but still don't get. if you have time explain this to me please.
@BlushinGun
@BlushinGun Жыл бұрын
@@tigran.zakaryan You can place a Print (name1, name2) before the If statement so you can visualize what’s happening. If you still don’t understand tell me what’s confusing you exactly. Sorry for late reply
@Grifanos
@Grifanos Жыл бұрын
@@BlushinGun Hi, I feel the same way. I've added the print statement, but the way Suzanne already is in the first place? It looks like the first task of the sorted method is sorting, and then calling our captainFirstSorted.
@SmartMoneyCookie
@SmartMoneyCookie Жыл бұрын
@@Grifanos I did the same thing. Adding print("\(name1), \(name2)") before the if statement but it shows Suzanne is already in the first place too 🤣 I've been trying to understand this for an hour and still don't get it. In this chapter, I don't think understanding closure is the hard part. Understanding this "Suzanne" first function is the hardest part.
@softwareengineer2297
@softwareengineer2297 Жыл бұрын
You are so good with ur dogs :) keep on running!
@gregdurfee1915
@gregdurfee1915 2 жыл бұрын
Hey, Paul, is this a correct version of a closure? let whyUseClosures = { print("Because you can use fewer lines of code in many places!!!!") } whyUseClosures()
@humphreyhanson
@humphreyhanson 2 жыл бұрын
Somewhat understood the workabout but got lost into thier functionality. Having to assume they come in handy with variable or constant asignation
@themilkyguey
@themilkyguey Жыл бұрын
For anyone still trying to figure the section with "let captainFirstTeam" in terms of the boolean outputs, I understood best when taking another commenter's suggestion. Blushing Gun stated: "As a beginner..." (hopefully he doesn't delete this comment lol) If you swap the return true to false in the first 'if name1' statement, and do the same for 'if name2' by swapping it to true, you'll see the output shifts the desired name, "Suzanne" to one other side of the spectrum. If you play around with the code further, you could try swapping the final return line "name1 < name2" and seeing what it does. Sometimes I find this the best way to help me understand the syntax when I find myself confused. Hope this helps someone!
@stuckhere90
@stuckhere90 2 жыл бұрын
I still do not get it. Why not just call the function with parameter? To me, closures simple mean to give the fubction another name. So what? I see no advantage.
@GabeColors
@GabeColors Жыл бұрын
Right?
@natgenesis5038
@natgenesis5038 Жыл бұрын
True
@yvan2563
@yvan2563 Жыл бұрын
Indeed. "How to create and use closures" is meaningless if you don't explain what they are, especially given their similarity to regular functions. This video might as well be titled "How to create and use Jabberwockys".
@mcquinmadtha
@mcquinmadtha Жыл бұрын
Not sure if this helps anyone. Looking at the teams array ["Gloria", "Suzanne", "Piper", "Tiffany", "Tasha"] this is how the logic works: Since the captainFirstSorted takes two variables, the second value in the array is compared to the first so I have put some print statements and this is how it looks like Suzanne less than Gloria true - (which means Suzanne is 1,Gloria is 2) Piper less than Gloria false - (which means Suzanne is 1,Gloria is 2, Piper is 3) Tiffany less than Piper false - (which means Suzanne is 1,Gloria is 2, Piper is 3, Tiffany is 4) Tasha less than Tiffany true - (which means Suzanne is 1,Gloria is 2, Piper is 3, Tasha is 4, Tiffany is pushed to 5) Tasha less than Piper false - (which means Suzanne is 1,Gloria is 2, Piper is 3, Tasha stays the same at 4, Tiffany is pushed to 5) So based on this, the sorted array is ["Suzanne", "Gloria", "Piper", "Tasha", "Tiffany"] To explain a bit further, lets change the order of items in the array to ["Tasha", "Piper", "Tiffany", "Suzanne","Gloria"] Piper less than Tasha true - so Piper is 1, Tasha is 2 Tiffany less than Tasha false - so Piper is 1, Tasha is 2, Tiffany is 3 Suzanne less than Tiffany true - so Piper is 1, Tasha is 2, Suzanne is 3, Tiffany gets pushed to 4 Suzanne less than Tasha true - Piper is 1, Suzanne moved to 2, Tasha pushed to 3, Tiffany at 4 Suzanne less than Piper true - Suzanne moved further to 1, Piper pushed to 2, Tasha still at and Tiffany at 4 Gloria less than Tiffany true - Suzanne 1, Piper 2, Tasha 3, Gloria comes at 4 and Tiffany pushed to 5 Gloria less than Tasha true, Suzanne 1, Gloria moved to 2, Piper pushed to 3, Tasha moved to 4, Tiffany at 5 Gloria less than Piper true - Suzanne 1, Gloria still stays at 2, Piper at 3, Tasha at 4 an Tiffany at 5 Gloria less than Suzanne false - Suzanne stays at 1, and then comes Gloria, Piper, Tasha and Tiffany Result is [“Suzanne", "Gloria", "Piper", "Tasha", "Tiffany"] Must be a silly explanation to some but this is how I understood how this works
@ferbenavides98
@ferbenavides98 Жыл бұрын
I disagree when you say void is nothing. I get what you are trying to say. But I believe that makes more confusion latter on for a new swift programmer. Void is an alias for an empty tuple. Tuples are also types in swift. So, definitely empty tuple it is something.
@whiterockjoe
@whiterockjoe Жыл бұрын
Swift Closures are easy if you think in Javascript. In Javascript 'speak' a Swift Closure is simply a callback function, which can be a regular function declaration or an anonymous arrow function, and which is passed as a parameter to an higher-order function. The main difference is the function type [ ( param: paramType ) -> ReturnType in ] that must be included at the start of the function code block: { function type + function code block } Although this has been well explained here.
@theflyingsolo
@theflyingsolo 2 жыл бұрын
Paul Hudson is the Pope of the Holy Church of Swift and good Lordy he’s a’ Preachin!
@thomaswahahauw560
@thomaswahahauw560 2 жыл бұрын
Fking love you mate!!! God bles you
@abdou023
@abdou023 2 жыл бұрын
The sorted function could have been explained better.
@POMbl4X
@POMbl4X 2 жыл бұрын
Fank You
@Jeff-zc6rr
@Jeff-zc6rr 2 ай бұрын
I'm sorry horrible example because we don't know the implementaion of sorted. How about creating a custom sorted and explain how the "anonymous" function performs.
@antlister
@antlister 2 жыл бұрын
somebody give me 2x paracetomol tablets please....
@navjotsingh2251
@navjotsingh2251 2 жыл бұрын
*Hands you 2 paracetamol tablets*
@lucasribeiro4702
@lucasribeiro4702 Жыл бұрын
my god, how can i be so dumb? this does not enter my head at all
@twostraws
@twostraws Жыл бұрын
Please don't be so hard on yourself - closures are one of the most complicated concepts in Swift, which is why on the accompanying page for this video I say repeatedly that they are difficult: www.hackingwithswift.com/100/swiftui/9 If you find closures difficult, it not because you're stupid. In fact, I think it just means your brain is working correctly - closures *are* difficult!
@lucasribeiro4702
@lucasribeiro4702 Жыл бұрын
@@twostraws thanks mate, I'll keep pushing
@AnotherCG
@AnotherCG 4 ай бұрын
Is it needed no. why do it ? because the apple God told me so.
@jasonjackson55
@jasonjackson55 2 жыл бұрын
interesting fact: Swift was actually named after famous singer Taylor Swift
@eotikurac
@eotikurac 11 ай бұрын
i have to end it here. this isn't for me. way too complex to listen to and process and we're not even at day 10. watching and rewatching a 20 minute video just to not get it in the end when i need to make something with this thing seems like a waste of time. the last exercise with all the error catching was too much too soon and i know it's only going to get worse from here on. i don't understand where do you guys find the motivation to keep going. if you go back to the start, this whole 100 day course is just enough to land you a entry level job. absolutely ridiculous.
How to create and use protocols - Swift for Complete Beginners
17:23
Amazing weight loss transformation !! 😱😱
00:24
Tibo InShape
Рет қаралды 67 МЛН
Викторина от МАМЫ 🆘 | WICSUR #shorts
00:58
Бискас
Рет қаралды 5 МЛН
A little girl was shy at her first ballet lesson #shorts
00:35
Fabiosa Animated
Рет қаралды 17 МЛН
How to create and use extensions - Swift for Complete Beginners
12:33
How to create your own structs - Swift for Complete Beginners
13:23
How to use Functions in Swift | Swift Basics #5
36:25
Swiftful Thinking
Рет қаралды 18 М.
Learn JavaScript CLOSURES in 10 minutes! 🔒
10:58
Bro Code
Рет қаралды 16 М.
Swift Closures Explained
14:23
Sean Allen
Рет қаралды 62 М.
Why SwiftUI developers aren't learning UIKit
11:24
codingKo
Рет қаралды 755
How to handle errors in functions - Swift for Complete Beginners
11:16
Swift Closures: @escaping Explained
4:45
Sean Allen
Рет қаралды 45 М.
Todos os modelos de smartphone
0:20
Spider Slack
Рет қаралды 66 МЛН
Xiaomi SU-7 Max 2024 - Самый быстрый мобильник
32:11
Клубный сервис
Рет қаралды 554 М.
low battery 🪫
0:10
dednahype
Рет қаралды 1,8 МЛН