Closures

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
good morning good morning welcome again to a swift module here we are talking about closures today what are closures closures are blocks of code that can be passed around like variables so they're known as first class citizens okay all the things closures could do they could capture references of their surrounding context closures are also known as reference types very similar to classes we'll talk about classes later in a different module um so let's get to it let's talk about what closure syntax looks like so here i could create a closure i'll call it closure i will type auto take my closure and we'll go over this code so very similar to say a variable that's why we call it a first class citizen because very similar to variables where i could create a variable name type annotate this and give it a name alex here very similar with closure syntax i could do the same thing so here i'm declaring a closure call it closure and it doesn't take in any arguments it does not return any arguments so this is very similar to our function here right our function that would be the function um so for example we have a function some function like that right so here very similar so closures are very similar to functions um here i have my parameter list here i have my parameter list here i have my return arrow here i have my return type okay in our case here we are not returning anything i could just a return void or i could just do this it doesn't return anything oh i could return void explicitly but here i am not returning anything um so here i need to specify this or i could also say void like this but my closure does not return anything so let's continue on so this is the closure definition if i option click on closure our compiler will show us that it's a closure doesn't take in any arguments doesn't return anything if i option click on my function it doesn't take in any arguments doesn't return anything if i was to return a value it should be like this here i'm returning an integer closures also could return values we'll come to that later all right so let's continue on my closure as it stands it doesn't have an initial value like here i have an initial value of alex but my closure doesn't have an initial value so how can we initialize a closure well we have the equal sign and whatever we want to assign it to is going to be to the right side in our case here our closure begins the body of the closure begins with a curly bracket ends with a curly bracket again very similar to our function the function body the function body starts with an open curly ends with an open curly our closure body begins with a open curly ends with a open curly in our case our closure doesn't return any value very similar to a function here i could just say print inside function body so since my closure here is not returning anything i could simply just say print and give it some statement say closure executed okay as it stands i haven't called my function to call my function explicitly i have to basically say some func like that and this is going to call because right now this here is a function definition right so this here just to review this is a function definition it defines what the function is but the function doesn't get executed until it's called on line 16. so here this is the function call very similar with our closure we define the closure on 9 19. so here this is the definition but to call our closure we have to same sort of syntax i'll call my closure like that and it doesn't take in any arguments so i just pass in an empty parameter list and if i was to run my mac os application i just press command r it runs my app if you're in playgrounds you could totally do this in playgrounds my playgrounds was not working it wasn't that stable today so i'm using a command line application a mac os command line application so here we are executing so it says closure executed okay i think it's just xcode in general today okay we might have to move this over to rebel because my xcode is currently not stable unfortunately let me create a rebel environment and we will move over to rebel okay we'll probably work with it for a second and if it's still acting up i'll move over to rebel so here we were able to execute our closure we have closure executed let's keep going so closures as function parameters right again we said we could pass closures um around very similar to variables so here let's go create a new closure okay i'll definitely have to move over to rebel so let us let us copy next second let's close this out okay all right so you could continue using playgrounds um i'm assuming your playground is probably more stable than mine at this point um but that's all okay this is very similar to playgrounds here we are in rebel and let me just run our code so we back in the same spot that we were okay so here we are um i executed my closure and i need to call my closure or not in other words um yeah let's call the closure so closure and run this particular closure and hey it says closure executed right because we executed the closure and all what it does is print closure executed okay let's continue on let's talk about closures as function parameters and we'll also talk about uh trillion closure syntax and what that looks like so here we'll create a function called reading and what does greeting take greeting takes in two arguments the first argument is the name and the second argument is a closure in our case i'll call the closure action and let's go over what that looks like so here i have a closure it's called greeting um greeting takes in two arguments or two parameters here first parameter is a string second parameter is a closure as we saw closure syntax here this particular closure doesn't take in any arguments doesn't return any values okay now let's continue on inside our function body with print will print the name of the person we'll just say hello and we'll use string interpolation and we'll say hello name whatever the person name is and lastly we'll execute the closure action so action is whatever um the person wants to to add to that particular function right we'll see what that looks like when they call greeting so in on the call side when i'm calling greeting i'll say greeting i'll pass in an argument bob okay so that's a function call passes an argument bob i also have a closure here so since i have a closure here as my last argument or my last parameter in my function i could simply use what's known as trailing closure syntax training closure syntax basically looks like this i have a open curly followed by a closing curly bracket and this is the closure basically so this is action here right action again doesn't take in any arguments doesn't return anything so i could now execute any block of code i want between the two curly brackets here in my case i could simply say [Music] print and say um name has been printed okay again this is a function call it has two arguments my first argument is a string bob my second argument is a closure and i just use trading closure syntax so here using trillion closure syntax okay great so now let me go ahead and run this replica environment and here i'll see hello bob hello bob and my turn included syntax i simply printed name has been printed here okay so what we saw here was closures as parameters this is a parameter here and we saw true enclosure syntax on the call side i used trading closer syntax to execute any extra code i wanted great let's now go on to talk about closures as optional parameters right what does that look like so here i'll create a function call it action action takes in a title a string and it also takes in a closure we'll just use the word closure again here we could give it a more explicit name but closure is fine so it takes in again two arguments right but this time our closure is going to be optional okay so closure here will be optional um how do i make that optional i put parents between the two uh parents here and i put a question mark to indicate it's optional let me make sure this is one two one more bracket and now i'll assign it a default value of nil okay so remember back when we spoke about functions we spoke about default parameters so here this is the default parameter it's set to nil okay so the user is up to the user if they want to use this closure or not right it's an optional parameter in my function body what am i gonna say i'll say print and put in a string here the title of the action is and whatever the title is here okay whatever the person put the title as okay now let me go ahead and call my action function and i could pass in some title here it's looking for a string and here i could say learning about closures okay just like that learning about closure is great now let me go ahead and run my code and here i'm seeing in my console it says the title of the action is learning about closures i pass it in this argument here it printed here and again the closure is optional earlier with our greeting function the closure was required i had to put in this um this block of code here if i remove this we'll get a compiler error right missing argument for parameter action in call okay because this is required it's not optional this parameter is not optional but in our case here this parameter is optional so it's up to us if you want to pass in a closure a trading closure or not here if i want to pass in a trading closure i can and say action is complete for example i could say action is complete here action is complete and now if i run my code i'll see the title of the action is learning about closures and did i print it out let me run it again oh right so here um we haven't executed our closure so here it's optional so i simply need to say closure call my closure and again it's optional and if i run this code again i'll see action is complete okay so again it's optional if i do not have this block of code and i run my code right nothing happens because this is optional here right so even if it's executed there's nothing to execute but if i do pass in a block of code here and i execute the closure and i run the code it will execute action is complete okay so you have two options you can make your closure optional if you want the user to have a choice or you could make it required meaning the user has to implement this closure okay great let's move on to escaping closures everything we've done so far just for context is known as not escaping or non-escaping enclosures so when we started off with our closure here um action is a non-escaping closure closure here is also non-escaping okay and now we'll see an explicit escape enclosure and we'll define what it is so first let's define a class call it blackjack okay what does blackjack take blackjack takes uh will declare will declare a closure called game score game score basically will capture the score of the game um so here let's just put in an integer so here this is the first time we'll see a closure capturing a value um so let's actually see what that is here um game score captures an int value remember earlier when we spoke about closures capturing values so here uh capture references so our game score will capture the value of whatever the score is for the blackjack game okay so here we defined a closure it's called gamescore our blackjack will have an initializer this initializer will basically take a game score which is a closure okay so again here our closure should be matching game score same right so it takes an argument which is an int doesn't return anything great and next we will uh set our game score itself to the game's call passed in just like that and we'll define one more function in our blackjack let's say function uh call it play and what does play do well play basically calls game score and it passes a random integer it passes a random integer and this random integer will begin from say 18 including 21. okay so let's talk about what's happening here so we declared a closure they find a closure called game score game score takes in an argument an integer and it doesn't return anything so fast it did we have an initializer here it takes in a game's call closure sets itself to that game score passed in and that's our function now if we run this code we'll get a compiler error here let's see what a compiler says it says error assigning non-escaping parameter game score to an escape enclosure so here game score here is an escaping closure so game score is and at escape in closure why if we store a closure or if we use a closure if we use as a variable as a variable in an object we have to market escaping we have to mark this closure at escaping because what happens our initializer initializes game score it returns the result but our game score hasn't been returned yet it hasn't even been used yet it will be used when we call play right when we call play it will be used so here we're using this closure game score as a storage mechanism so we have to mark it at escaping so right here inside of our initializer parameter list we have to mark this closure coming in as at escaping so it matches so at escape enclosure this one here needs to match this at escaping i can have a non-escaping closure and assign it to an escape okay so now if we run our code everything compiles and we are happy now let's go ahead and test our blackjack so we'll test it again we have a class here it's called blackjack i'll create an instance of i'll create an instance of blackjack here blackjack and this instance takes in one argument which is a closure so here i initialize it right it takes in one argument which is a closure again uh the rules of a closure if it's um the last argument in a function you could use trading closure syntax here which we are using and we have one argument which is an integer so here i could call my integer i could give it some name in my case core is the argument and the in keyword is needed here as well so score is just a name like earlier we had our closures they had no arguments so this closure had no arguments right this closure had no arguments but this particular closure has an argument so we have to also define the argument here i'll give it a name which is score score n score enclosure right so now i could use this score whichever way i want um it doesn't return anything so basically if i run this code we should be good it should compile because there's no return right again our closure is defined as this it's an end doesn't return anything but i could use my score whatever the score is here again closest capture values so whatever the score is here that this game captured i'd have access to it online 59 okay so whatever again whatever score that this game score captured here on 955 i'll have access to it in my blackjack trading closure here so now i could simply print uh score score is whatever the score is and this is going to be a random score from 18 to 21 okay so now let's go ahead and run our code and hey look at that we got blackjack score is 21. great if i run this call if i run my project again we got 18 this time okay so we were lucky the first time this time around great um let's keep going on here so let's now talk about shorthand syntax and what that even means okay so let's go ahead and define a new function we'll call it um operation operation itself takes in two arguments a which is an integer and b which is also an integer and it takes in a third argument which is authored parameter which is an action and this time action takes in multiple arguments and it returns void doesn't return anything so here we have three parameters the first two parameters are integers and the third parameter is a closure that closure takes in multiple arguments okay great and it doesn't return anything how are we going to use operation well we'll simply print num times num actually we're not printing them times now what we want to do here we want to use action to capture what num times num is the only thing action takes action needs to take into argument so if i run my code right now it will error out because here it says that missing argument for parameter one in call so this guy misses arguments so if i put in um a right it still needs one more argument right missing argument for parameter two right takes two arguments so here i pass in a and b right so that closure as it as lies right now doesn't do much it just captures a and b i could actually pass a and a it wouldn't care right if i run this code right it doesn't really care because all what it cares about i need to get two integers okay so here we pass a and b we capture those two values so here action is capturing value a and value b okay so that's what's happening here so far great now let us go ahead and use or call our operation so if i call operation i need to pass it arguments i'll pass it a and b in that case i'll pass it five and i'll pass it four so far so good we also have a third argument we have to pass in here which is the closure and again this is a closure so i could use trading closure syntax here so using trillion closure syntax okay our closure takes in two arguments so i could just give them names like call it value one comma value two in right and now it doesn't return anything so it's up to me to execute whatever command i want in my case i'll just print i'll say um add in values together equals just add the two together so here we have value one plus value two and i will go ahead and run my rebel so here we'll see adding values together equals nine right so if we have five plus four it equals to nine okay so here we had a longer form way of printing this out and now let's talk about shorthand syntax what does that look like so here we shot in syntax i'll call my operation again i'll pass into arguments let's just pass in 10 and 5. and now i simply enclose your syntax and now instead of saying value 1 and value 2 in this i'll just simply say um i could simply just say print actually because we want to print the values and i'll say dollar sign zero so dollar sign zero here represents the first value i have two arguments so dollar sign zero represents the first value multiplied by the second value which is dollar sign one so this is shorthand syntax so dollar sign zero is the first argument dollar sign zero dollar sign one sorry is the second argument if i had a third argument it would be dollar sign two okay so this is how you use shorthand syntax with closures dollar sign followed by the value position in that case zero position is value one one position is valid two here and now if i run my code uh what do we have 10 times 5 so we should see 50 being printed out and here we see 50 being printed out okay so this here is using shorthand closure syntax awesome great let us keep going on so now we'll talk about closures with arguments well we spoke about closures of arguments already this is basically a closure here with arguments um but we'll just do one more just to drive it home and here we'll say let is even i'm defining a closure this closure takes in an argument an integer it returns a boolean to indicate if it's even or odd i will give it an initializer in my case here i'll simply say return i don't even need to say return because actually we'll talk about return so i could say return dollar sign 0 mod two should equal to zero right what does that mean um again the argument in that case we have one argument if i um take the mod operator of it the remainder the remainder operator it should be to it should be equal to zero if this is even if this is even it should be equal to zero if divided by two it should be equal to zero so i could use this directly i'll say print is even and i'll pass it some number 10 and this is just gonna say true return some boolean value run this and here we see true okay because when i execute is even again it's a closure it takes in one argument which is an integer it returns a boolean value so it just returns true i could remove this return and run my code again and i'll still get true this is known as implicit return enclosures so implicit implicit return enclosures okay so we don't need to specify return here the compiler will infer that this returns a boolean value because this equates to a boolean value it just returns that value great next let's go to closures as return types right this gets a bit more interesting again going back to when we spoke about closures as first class citizens they act the same way as constants and variables we could return them from functions we could pass them into functions right um so here we'll actually return a closure so let's define some closures so we'll define add add takes uh two ins and it returns an int we will um give it an initializer like what does it do it basically um what does it do it basically takes the first argument and it just adds it to the second argument okay that's basically what that does right um let's just copy this and create subtract so subtract is very similar subtract again takes two ins right two numbers you want to add together and then whatever the value is the result is it's an also an integer so here we will basically say zero minus one again two arguments we define it as dollar sign zero dollar sign one this is the first argument this is the second argument okay so here we are we have our two closures and we want to return so let's create a function here we'll call our function random random operation what does random operation do random operation just returns a closure and that closure looks like this int int returns an int right so we have our function here it returns a data type and that data type is a closure the closure is very similar to our add and subtract closures two integers returns an int okay next we'll create an array of operations and that array has add and subtract and simply will return operations dot random element and this is an optional so we'll just uh give it a default of add so we'll just basically get one of those closures return it okay so that's basically our function let's just run this make sure we have no errors we are good so now let's go ahead and call call our random operation so random operation just returns a closure this is what we're talking about closures as return types this is a closure as a return type so now i will say operation and let me get a random operation so random operation doesn't take in any arguments but it returns it returns a closure so this operation here is a closure okay now my closure i could use it like a function so this operation here operation is a closure and what does it look like it looks like this right takes into arguments returns an integer so now i could simply say print operation and pass it to integers in that case i'll pass it five and um eight for example so here i process five and eight operation it could be add or it could be subtract we don't know it's gonna be random so now if i run my code and i have minus three so let's guess what it is it's subtract it returns subtract this time okay five five minus eight is minus three if we run the code again let's see if we get add this time we still get minus we did one more time and we got 13. this time it added them together okay so again just to review we defined two closures add and subtract they both are identical in their signatures but the definition their initializations are different their bodies are different what they do is different one adds the two operands together and the other one subtracts and we have our function our function here returns a closure doesn't really matter it doesn't care what the inside of the operations are but all it cares about is the arguments in that case it returns to ins or it ticks into ends rather and it returns an integer so that's what ad does that's what subtract us and now we could use it get a random operation and execute the operation here on line 91. great so we saw a lot of closures already um now let's take a look at some built-in closures as we come down here to the close of this so map is very popular what does map do map transforms basically map transforms um elements in a collection we could best see that as an example so here um i'll just create an array so just say map array one two three four okay and now i'll just say map results and what we want to do basically is um actually let's just call this square results so square results basically what i want to happen is go through each element again transforms each element transforms each element in a collection and returns the resulting array that's what map does so each element we have four elements here it's going to go through each element do a transformation and return the result the transformation is up to you what you want to do in our case here with map we will call our map array and we'll say that map will use trading closure syntax which is the easiest way to do this as far as readability and all that so here we'll use trading closure syntax that we've seen because map takes in a an argument which is a closure so here we just use trading closure syntax think back to our early examples here where um for example we had um we had ease even takes in a closure right actually let's go to the function we have a function here uh let's go to our initializer that's fine our initializer here takes a closure it's a function um we call blackjack we just use trading closure syntax so same as map we'll just use trading closure syntax and what we execute inside the body is up to us as far as the logic but keep in mind we have to pass in one argument map takes one argument so if i call if i call our function right now i'll get an error because it says context type foreclosure argument list expects one argument map takes one argument that argument is the element in the array each element represents that argument because it needs to go through each element to perform the transformation in our case we want to square each element so we're just passing down sign zero times dollar sign zero i can say dollars and one because there's no it doesn't take in two arguments it just takes one argument it's up to us what we want to do with this argument in our case we just want to multiply it by itself so we just say times yourself by yourself in our case now i'll simply say print square results and now i should get 1 4 9 16 which i do get one for 9 16 because it's squared each one return the result and we were able to print it out let's talk about filter so here we'll say filter array and we will create a very similar array here okay what do we want to filter by filter as the name implies it just returns an array of filtered results based on a given predicate when i say predicate like whatever the condition is a given condition is a condition predicate cool great um let's go ahead and use it so here i'll say let filtered results equal to my filtered array dot filter which is the function which is the closure which is also known as a higher order function since we're talking about built-in functions here so just forced to recap here i did mention higher order function a higher order function is a function that takes another function or returns a function right so that's basically what um our map filter reduce sorted compact map does right there are higher order functions the tick functions or the return functions um cool great so filter array filter um and in our filter again we're using trading closure syntax here what we'll say will basically say my argument what do i want to filter it by any filter you have to do it has to return a ball in my case here if i say where the argument is greater than four for example that returns a bull so that's fine so think of filter filter looks like disclosure right it takes in in our case an int and it returns a ball so if we were to think of what the closure filter looks like this is what the closure looks like it takes in an int returns a ball right this is an end returns a ball this is this returns a boolean value okay um but filter works with any type filter could work with strings any type right so for now we're just working with ins but think of it if you have to think of any type you could think of t as a generic type but here we'll just skip to integers and now if i go ahead and i print filtered results here i should get back five six and seven which i do because what do we say filter this out this array where the argument value is greater than four if we go through each is one greater than four false is to greater than four false is three greater than four false is four greater than four false is five greater than four true so that's one is six greater than four true that's two is seven greater than four true that's three so that's three um three var is returned okay um next let's go ahead and talk about reduce so what does reduce do here i will say um i'll just create some values we'll say one two and ten it's fine and what we want to do basically we want to add all those values together reduce is perfect for that what does reduce do combines values given a closure okay all right again better done in an example here we'll say um let's just say sum that's what we'll be doing and we could say values dot reduce so reduce takes in two arguments the first argument is an initial value in our case we want to add so we'll say zero is the first argument and the second argument is a closure so if we were to do this um long form actually let's just do the short form right now um short form we just the second argument is a closure here we just pass in plus which is a closure okay it's a closure because it is a function very similar to our ad think of our ad here as a closure so whatever we pass so the add operator itself is a closure so it's this whole definition there it takes into um ins returns and int this is very similar to this okay so now i basically have added all the values together and now i could just print sum and sum is 13 10 plus 2 12 plus 1 thirteen okay uh next we have sorted we have compact map and um cool all right so that's fine let's go through sorted so what do we wanna do let us create some names or rather let's just do characters all right we'll create a character array let's create a character array and give this some characters so z a and d okay so we have uh an array it's unsorted and we want to go ahead and sort it so let's just call this sorted characters and we will this is an array we'll call sorted on it so that itself is also takes also a closure so there's various there's various sorted there's sorted way you just pass in sorted and as without arguments and it just sorts it ascendant by default but if you don't want to sort by default ascendant or you want to pass in your own sorting closure you could do that using sorted in our case what we want to do let's start off with the default ascending for example um it takes into arguments so sort of takes into arguments data sign zero data and one map takes in one argument data sign zero okay cool so now let's go ahead and print and see what the results are so results of our solid characters and run this so here we have ascendant a d z okay if we say we want it to be sorted descending so this let me just put some notes here so less than sign is ascending order and more than sign is descending order okay so ascending means going up from small to large from a to z ascending descending is the reverse so if i was to flip this around like that now it's gonna go from z down to a okay z down to a so this is sorted very powerful um the last built-in function which will do there's many other building functions but the last one we'll do is compact map so with compact map compare map is very very useful right so we really really want to be able to know and come to compact map when we want to so compact map let's just create um let's create uh let's create grades for example so i have an array of grades um they're all strings i have 89 i have 90. i have 90 i have 75 and i have 80. great so here i have an array of strings this is what it looks like this is an array of strings great now i want such that to only get valid grades um because right now 89 is valid that's a number 90 is valid that's a number 90 is not valid that doesn't translate to a number so what i mean by that if i take the um if i take the int initializer and i pass in a string it will try to convert it to a number if it's not a number it will return middle so basically what compact map could do or will do for us is first see if this is a valid number if it is return it as a valid value if not it's nil don't add it to the resulting array so let's go ahead and do so so here we'll call this valid grades and we will call grades we'll call compact map on grades compact map also takes in a trading closure here and what do we want to do well each argument or each element is a string so we want to take that string i'm going to convert it to an int so here we will say int try to initialize it to a varied integer this integer here that takes in some string like this is a fillable initializer is a fillable initializer what does that mean it returns an optional so if it returns an optional if it's nil doesn't exist or wasn't able to be created so if it wasn't be able to create it returns nil our compact map won't return that result of nil basically compact map removes removes near values that's basically what it does so now if we print valid grades and run our app we'll get back 89 90 and 75 in the order in which it's valid right because remember arrays keep the order so here 90 is not a body number 80 is not a valid number so compact map very very very powerful next let's go to take a look at chain enclosures so you could all the closures we've seen so far we could chain them together to to get back some sort of result so here let's create an array what's there we're gonna be so we have one nil and five right optional array of integers we could use compact map which we just saw on it we could say compact map remove all the nil values which is what this does so it goes through each value if it's nil doesn't return it now we could also say when you return those values for us also map it and what does map do here in our case let's just go ahead and square those numbers together so let's just do multiply each number by itself so the result should basically be 1 and 25. let's go ahead and print result and here we should get back 1 and 25 1 times 1 is 1 5 times 5 is 25 nil gets rid of nail doesn't exist so if we run this we'll get back 1 and 25 so here we are able to chain closures together and you could keep chaining them right i could have an x dot here and say do something else like reduce right which we can do we could say reduce here and reduce we'll start off with zero and we'll say add those two numbers together so now we should get back 26. right which we do get back 26. so now get rid of this and now we just get back 26 right so you could chain you could chain um closures together and sometimes what you do see as far as like readability you see things like this where you basically keep them in order like that so it's like compact map first they map then reduce so on and so forth very powerful very functional uh okay lastly let's do a simple exercise here um let's rewrite filter so this is a challenge we'll just do together if you want to do the challenge feel free to pause the video here and come back and watch the result after okay so it's a nice little challenge to build upon what we just learned and this challenge says rewrite the built-in filter function so basically we just saw filter and we saw what filter did filter takes in an array in our case this array here and it basically does takes a closure and then returns a ball so in our whole function we'll have um two arguments one argument will be an array and the other argument will be a closure so two arguments so go ahead and pause the video and you can come back and complete the challenge okay so here we have our function we'll call it custom filter that's fine custom filter is fine and as we said we'll have two arguments the first one will be let's just call it elements um and also let us make it generic so it works with any type actually first let's make it not generic let's just make it an array of integers and then we'll convert it and then this returns a resulting array because remember filter just filters an array and our second argument is let's just call it filter it's a closure that closure takes in an int an end and it returns a bull very similar to what we said earlier with what um filter does right returns a ball great in our body we'll start off create an array we'll call it filtered results which is an array of ends which is empty right now and at the end will return filtered results great next we'll use a follow-up because remember we have to go through each element so this is the linear so all those functions we've seen so far are linear right as far as runtime is concerned so for element for element in elements what do we want to do well we want to check if we pass in filter which is the closure that closure takes in an argument which is an integer element so if this is true whatever predicate gets executed here we don't know um so if this is true that means i want to add it to my resulting array so if it's true add it to the array so filtered filtered results that append element okay that's basically what filter is so let's walk through the code um we have our empty array we go through each element we check if that particular element um satisfies a given predicate or a given condition if it's true here add it to the filtered results and at the end return filtered results so let's go ahead and test this so we'll create um numbers a numbers array one two 3 4 5 6 7 8 9 10. and basically we want to get back even numbers right this is our test we'll call our custom filter it takes in an array we'll pass in numbers takes in a closure will use trading closure syntax we'll use shorthand syntax as well and we'll say dollar sign zero right one argument right just takes in one argument at a time you see that one argument is element so for each element check if it's even we'll use the mod operator we'll divide it by two and we'll get back the remainder if it's zero it's even if it's not zero it's not even it's odd so here i'm done i just go ahead and print even numbers and now i should just get back even numbers so let me run my code and we get back even numbers 2 4 6 8 10 so we were able to build the built-in we're able to build our own filter um based on the filter uh the built-in filter function i'm using a closure so at the end of the day um this is just exercising our understanding of closures so here we have a function that takes two arguments one of those arguments is a closure we're able to use the closure here on line 139 um and that closure took in an int element here is an int okay cool um if you want to convert this like say i want to [Music] um let's see say i want to get letter a right and here we have some characters let's get back all the a's here okay i have a i have b i have a i have a so basically we want to get back three a's right now if we have if we were to use our filter function let's just create this and then say um characters this i need to type rotate this not really but that's fine let's just type annotated character it could just remain a string that's fine um and now i just call my filter so custom filter and custom filter takes in characters and basically what i want to do is a filter where this character equal to a well that's not going to work right now right if we run this it will tell us invited well first of all if this was existing before characters again or more characters and here just call it small characters and run the code again so here we'll see cannot convert value of type character to expected argument of type int because right now our function only works with integers but wouldn't it be cool where our function doesn't really care if it's ins or strings or doubles well here comes generic right um we haven't covered generics yet but i could give us a quick glimpse at what generics could look like so generics allow us to work um allows us to have our code basically flexible right flexible as far as like i could use this function multiple ways on multiple data types that's what generics allow us to do instead of writing the same custom filter five times or whichever amount of times you want to be able to use this i could use a generic so here i convert this function to a generic function and then my generic type would just be called type t i could call it anything i could call it element u in our case it's just going to be type t so everything here is going to be converted to type t bull still exists because it has to because i'm trying to see if it's true or false but what i return here is also type t uh filtered results has to be type t it could be strings ins so it's now generic and we should be good here so let's go ahead and run our code and see if we are also good all right great um the last thing i did not do was print let's just go ahead and print print letter a or letter a's we should have three here and we do have three okay so now our filter works on ends works on strings as well could also work on doubles or anything else you throw at it okay as long as it's able to yeah as long as able to there's no comparison but it just returns true or false so there's no constraint on that um so we are good okay we covered a lot today with closures and there's a lot more to cover if closures closures is one of the most complex parts of the language um so knowing it is very very important um so please please please review as much as you can with closures um they're great right so here we are let me just review from the top what we did today so we started off by defining a closure here we just call this var closure and closure takes in this doesn't take any arguments doesn't return any arguments um and what else we did we did a lot today one second let's go to the top so here we did close your syntax definition we need closures as function parameters and trading closure um syntax actually there's also multiple shooting closures now in swift as of 35.3 so let me just put a note here as of swift 5.3 we now have multiple trailing closures okay so here we just have one true enclosure but we could have three four right up to us what we want to do um closures as optional function parameters here i declare this this happens a lot when you have like a an alert controller for example you could pass in an action or not um we spoke about escaping closures and escaping closures also appears in network requests for example like if you're making a network call and you have a closure that particular closure has to be at escaping because again the function will return before the closure returns so anytime that happens you have to mark it at escaping shorthand syntax we spoke about that so we went long form then we went shorthand meaning dollar sign zero next we spoke about closures with arguments here disclosure has an argument which is an in also returns a type which is a bool we spoke about closures as return types we had two closures here add and subtract we had a function that ticks in actually it doesn't take in any arguments but returns a closure so here we are able to randomize a closure return it and make an operation on it so here we could return add or subtract we looked at built-in closures in swift map filter reduce sorted compact map we also chain closures together and lastly we ended up with a challenge we write the built-in filter function um cool all right as always thanks for watching see you next time
Info
Channel: Alex Paul
Views: 266
Rating: undefined out of 5
Keywords:
Id: Q0fahJeV4Zo
Channel Id: undefined
Length: 69min 23sec (4163 seconds)
Published: Wed Dec 16 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.