How to create and use closures - Swift for Complete Beginners

Поделиться
HTML-код
  • Опубликовано: 2 окт 2024
  • 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.hackingwit...
    Watch the full Swift for Complete Beginners playlist here: • Swift for Complete Beg...

Комментарии • 73

  • @tigran.zakaryan
    @tigran.zakaryan 2 года назад +16

    I still can't understand how the captainFirstSorted function is working.
    what is the logic of that function?

  • @thefelix1100
    @thefelix1100 10 месяцев назад +15

    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 9 месяцев назад +2

      Thank you sir, that's the only thing I was struggling with!

    • @monogidrat
      @monogidrat 4 месяца назад

      Thanks a lot, that was very helpful!

    • @iraklyoda4213
      @iraklyoda4213 3 месяца назад

      Thanks man. I got exactly the same feeling that Paul was not mentioning something regarding how sorted function worked.

    • @chris_tteg
      @chris_tteg 2 месяца назад

      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 Год назад +7

    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

  • @mauroabrantes5948
    @mauroabrantes5948 2 года назад +16

    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 года назад +8

      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 Год назад +1

      @twostraws we need an update that makes sense

    • @Vidadlaur
      @Vidadlaur Год назад

      I already died trying to understand it

    • @theoldrook
      @theoldrook Месяц назад

      Thank you @Munchkin303. I was trying to figure out how name1 and name2 got passed to the function in the first place. Does the sort function automatically pass two generic items from the list to its arguments?
      The concept of a closure doesn’t seem nearly as nuanced as the behind the scenes workings of the “sorted” function.

  • @spailsofficial
    @spailsofficial Год назад +4

    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.

  • @NathanBudd
    @NathanBudd 11 месяцев назад +3

    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?

  • @Jeff-zc6rr
    @Jeff-zc6rr 4 месяца назад +1

    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.

  • @ericvaish
    @ericvaish 2 года назад +6

    That was such a lovely explaination. Thanks mate!

  • @dereklei1746
    @dereklei1746 2 года назад +8

    When they say RUclips is a good place, they're probably referring to this Channel. Thanks Paul for such an enlightening explanation.

  • @mcquinmadtha
    @mcquinmadtha Год назад +5

    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

  • @all4ege
    @all4ege 2 года назад +4

    Oh my God!!! Thank for such a brilliant explanation!!!

  • @srome0711
    @srome0711 2 года назад +2

    Thank you for the reassurance I'm not a dumbass - I actually needed that.

  • @BlushinGun
    @BlushinGun 2 года назад +9

    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 2 года назад

      I did that, but still don't get. if you have time explain this to me please.

    • @BlushinGun
      @BlushinGun 2 года назад

      @@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

    • @GrifanoRide
      @GrifanoRide Год назад

      @@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 Год назад

      @@GrifanoRide 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.

  • @stuckhere90
    @stuckhere90 2 года назад +9

    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".

  • @leon.dev89
    @leon.dev89 11 месяцев назад +1

    I’ve had to watch this video about 5 times now. I think I’m starting to understand Closures 😅

    • @arulpraveen
      @arulpraveen 11 месяцев назад +1

      I just watched it once and I'm baffled. I didnt understand anything lol. Let me try 4 more times like you.

  • @theflyingsolo
    @theflyingsolo 2 года назад +1

    Paul Hudson is the Pope of the Holy Church of Swift and good Lordy he’s a’ Preachin!

  • @AnotherCG
    @AnotherCG 6 месяцев назад +1

    What I like most about these tutorials you make is you keep the font large something a lot of tutorial makers refused to understand

  • @antlister
    @antlister 2 года назад +3

    somebody give me 2x paracetomol tablets please....

  • @ОлжасБ-л4и
    @ОлжасБ-л4и 3 месяца назад

    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?

  • @Jeff-zc6rr
    @Jeff-zc6rr 4 месяца назад

    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?

  • @ejazmuneeb
    @ejazmuneeb Год назад +1

    pure gold secrets at free of cost for ios devs.

  • @alexpascal5403
    @alexpascal5403 2 года назад +1

    Coming from Python, Java and js. I have learned to both love and still misunderstand swift’s idiosyncrasies

  • @karammelkon
    @karammelkon Год назад +1

    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.

  • @chocomilkfps1264
    @chocomilkfps1264 Год назад +2

    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 Год назад +1

      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

  • @rogerrtewwr4723
    @rogerrtewwr4723 3 месяца назад +1

    one of the only good videos on closures I've found ... thank you

  • @abdou023
    @abdou023 2 года назад +4

    The sorted function could have been explained better.

  • @PatrickGrindelwald
    @PatrickGrindelwald 28 дней назад

    A clear explanation for beginner, great thanks

  • @AnotherCG
    @AnotherCG 6 месяцев назад

    Is it needed no. why do it ? because the apple God told me so.

  • @Drewbydrew
    @Drewbydrew 2 года назад +6

    Omg, I finally understand closures! Thank you Paul!

  • @YoAbaAba
    @YoAbaAba 2 года назад +1

    I love you

  • @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.

  • @jackle3002
    @jackle3002 Год назад

    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?

  • @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

  • @aniltodakar6449
    @aniltodakar6449 9 месяцев назад

    Nice and deep explanations. Thank You.

  • @lucasribeiro4702
    @lucasribeiro4702 Год назад

    my god, how can i be so dumb? this does not enter my head at all

    • @twostraws
      @twostraws  Год назад +1

      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

  • @JozsefNyulas
    @JozsefNyulas Год назад

    This made things clear. many thanks!

  • @gregdurfee1915
    @gregdurfee1915 2 года назад +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()

  • @ilgaralizada7206
    @ilgaralizada7206 2 года назад

    thank you for video

  • @sulthankios3997
    @sulthankios3997 2 года назад

    Thank u

  • @POMbl4X
    @POMbl4X 3 года назад

    Fank You

  • @themilkyguey
    @themilkyguey Год назад +1

    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!

  • @thomaswahahauw560
    @thomaswahahauw560 2 года назад +1

    Fking love you mate!!! God bles you

  • @eotikurac
    @eotikurac Год назад

    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.

  • @jasonjackson55
    @jasonjackson55 2 года назад +2

    interesting fact: Swift was actually named after famous singer Taylor Swift

  • @softwareengineer2297
    @softwareengineer2297 2 года назад

    You are so good with ur dogs :) keep on running!

  • @avafreak252
    @avafreak252 2 года назад

    Thank you! You explain the concepts very well

  • @martinkowollik1432
    @martinkowollik1432 2 года назад

    Great & very useful! Thanks!