Udemy

Intro to Generics in Swift

A free video tutorial from Bob Lee
iOS Instructor | Bob the Developer
Rating: 4.1 out of 5Instructor rating
1 course
1,620 students
Lesson 6: Intro to Generics

Learn more from the full course

Learn Swift 4 with Bob: The Intermediate to Advanced Swift

Functional Programming, Protocol Oriented, Value Oriented, Generic Protocols, Object Oriented, Swift 4

17:38:08 of on-demand video • Updated September 2017

Learn the difference between classes and structs and which one to use
Learn how to create generic enums, structs, classes, protocols
Get a taste of functional programming with trailing, auto, and escaping closures
Understand how objects are created and removed through Automatic Reference Counting
Understand potential retain cycle in closures, delegate, and class variables
Understand Swift is a protocol oriented programming language
Apply protocols such as Equatable, Comparable, Sequence, and IteratorProtocol
Execute Swift files using Terminal/Command Line
Functional Programming
English [Auto]
Kinds of lessons six of the Slive fundamentals that bothered Bolpur when you think about the were generics. What makes you think you probably thought about making a reusable and scalable code base right. B You were like me before you probably thought how. Of course not. Well that's OK I'm going to walk slowly you probably have seen those keywords such as T and you when you take a look at someone or someone else's code. Well this lesson let's learn what those mean when it comes to the moment you make sure you want to have the least amount of input they'll produce the maximum amount of output. In fact no code is the best code in the world because the process of writing code is actually making bugs along the way until but that we all leave in our reality. However as long as that code is it provides effective communication. Also you get the job done. Then why not just write as little as possible so he may focus on other jobs Swift. Generics will definitely help you with that. Wolken in true to generics will end this lesson. We're going to take a look at. I smell something. So what does mean by smelling in programming. Well go to coding practice in the lecture notes and then coding smells. Woman means bad feature something bad prediction that caused bad feature. All right bad feature right there. And the universal smell can be complexity and those duplication over use type literally means a lot of type strings available. You know when you type a lot you make a lot of mistakes because humans are meant to make mistakes and overuse DVR ins have led. Well we're not going to talk about this yet. So you don't want to have duplication. You to have complexity right. That's what I mean by smell something. Well I'm going to give you one example. This is how you did in the past when you first learn how to program. And then let's let's start with there. So let's say a couple of arrays available so like numbers high school GPA you know favorite people. Right. And also even numbers in the past in order to access this element. And what you need to do of was this is kind of the worst way you can ever do. But you kind of did some de-link this you know one by one when you first learn how to program right. Then later you realize a computer is actually pretty good at doing one thing at a time of doing the same task over and over. Soooo your son told you hey why not just create a for loop and make it happen. All right. So that is what you did. So you create a couple for a function right. That which allows it to print double element takes that array and then it's going to go through the foreign look and the prince Prince that each element right there. So same thing goes the string same thing goes to it. OK. So it's basically the same idea. So just to make sure we are able to run this coded nabes high school GPA I believe. Here we go you have this beautiful spinning out each element right. All good. But but you my thing are this is this and this is better than the Vorse way. But based on my advice based on many other people's programmer this is not the right way to go. This is this is a really hideous is this is bad. All right. You want what you want to do you just want to create a one function. Ok that does it all. How do you go about that. Well let me introduce you to generics. OK. That is a goal of this lesson. So first of all we're going to learn how to use generic function during function allows you to enter any type of game array can be string type or in type double type human type Karena type does matter. But you're able to enter it and then you're able to work with it. So let's create a generic function let's call it generic function and this could be a just pure function right normal function. But here to make sure this is something special. This is a different animal. You know see just type whatever you want to and you know just type for now and then value just type whatever you want. You can see the end to something. This is a brand name right. It's great value and it's going to be anything that comes on the left side on the right side. They have to match. So. So now what do you have is you have the ability to call this value use that parameter. So the type of anything is not defined. Anything is not undefined something called as a placeholder. You can just literally define it later in time. And there are many ways to define it Wolf. And for function they're not meant to be an example so you can say generic function. And if you enter Bob what's going to happen is the type of anything becomes string. OK. Anything becomes a rhino. In the past you defined that type of place with string but now it is not defined. You can only define it by putting the value so that it with. So right now by putting Bob here the type becomes what you call the string seal. And of course if you want to enter some number now the type of anything becomes one in eight. OK Javier's makes sense to you. Well in in instead of calling anything in programming in SWIP we tend to call it like generic functions call it T T which stands for type can print a value. That's how that's how people do it. In some call it whatever you can call it whatever you want you can call it my type but in real programming and swift we call the T. OK. Or are you OK. All good. So now how can you apply this generic function to do with this one. Well there's not much there's not much different. So all we're going to do is call it creative function print element k. And we're going to call t here to indicate this is a different animal. This is during a generic function called array. And to array what you want to call the parameter and this will be a type T placeholder has not been defined yet. It can be only defined by putting the value in it and because for element in array. You can say print element. Now let's see. Let's see. So print element and you ask it to enter T. So T is a placeholder I'm going to define how you define it. Well you can define it by placing a value. So I'm going to enter the high school GPA the T's double rainbow three double and automatically to t the type of T becomes double and is able to execute. The array becomes double right there. It happens as soon as you entered his high school GPA and also element print element and you can enter favorite people right there right. There was a string the T becomes string Wind-Up function. And here we go Walla. So compared this. All right. One two three for five compared to one right. 15 lines of code. This is Hedy's you that you don't want to do this. OK. When you do we don't create generic function. You are wasting time wasting lines of code. And if there's a better way if you're not implementing dad you are wasting time. We always look for optimizations. OK. So in a nutshell this is what the Swiss engineers say generic code enables you to write flexible usable functions and types that can work with any type subject to requirement that you'd find this part subject requirement is fine. We don't talk about it more. At the end of this lesson. OK. Again use generic code don't non-interfering you are. Doesn't matter. Use Nury killed all the time for your program for your Iowas apps. So not only you can use dinner coat with functions also meat you can also apply with strokes and classes or Gnome's doesn't really matter anything. It can be also used for protocols. We are talking about later later in later chapters. OK so I appreciate generic struck. I think it's important for us to just sort of with just non-generic code first to just to appreciate like to go with the past and then move on after and you can call it let's call it family and family contains a couple of members. It contains members and once. For now let's just empty create an empty array like the anti array like the we have a defined type String OK. And what you want to do is you want to push one end as you want to. You want to be able to append door ad to this member members or add the family member for the father mother. Doesn't matter. Call it fun. Push enter say so in member and there is just enter string and band members Dodd append and member. But you're going to see a problem. What the problem is don't ask you why don't you say self is immutable and what's happening is you need to say hey you're going to say call and mutating. OK well well I'm not going to talk a lot about in detail but when you were struck when you are attempting to mutate we call this right no member is no Ray-Ray. But when it Cola's push function what's happening to you or you're changing the value of members you're adding something you're mutating you are changing in zoo when you're working with it's own type on variable members pand it attempts to change it. You have to put mutating for it struck me. Struck in. Well we can talk about we're going to learn more about this has been instructing classes in a couple of chapters. Couple lessons later. So don't worry about it. All I'm going to say is if you need to put mutating for properties that you are trying to mutate it for struct Needham's. OK that is do quar get called that makes sense it does make sense. Well just hit wait for me a little bit. A couple of lessons later. So in order to create this object you have to do something like this. My fam family and you can push back. And now family members contains Bob right there happy and nice. Right. Bob there is definitely one book to be part of the family right. But but what if your family becomes all right. Your family comes home from the march and they use some sort of a binary digit to communicate members so they don't use A B and B they use like one two three four five six seven do. What do you do with this. Well you have to do something like this. Call it. You have to do something like number family and then you have to the changes to int and then you have to change just to int. It becomes very tedious. Right. I mean this is not this is bad. OK. This is not generic enough. And as you know you can smell this I smell this duplication. Right. And you don't want a code like this. This is hideous. So what do you want to do with you want to create a generic structure that allows you to create. It does matter members of a string are. And double doesn't really matter how to go about that. Well it's very similar to how we did it whether with the function. All you have to do is create a generic struct simply to also have just a generic fem and then you're going to do is put this placeholder let's call it whatever. Now let's call it anything it's called anything. And later in the change it to a little more professional name and the rest is a the of var members and the B of A T available t is a placeholder so we can define it later right. When you initialises object and you can say mutating function push we just copy this from the top and right there. And the members will be t t is not defined yet. We're going to define it later in time. What are you all you're now using. You hearing anything right now. Yeah I'm not used to using anything idiom used to use. So here we go. So here's a magic. You have the ability to put anything you can you can members can be screening can members can be in it. You don't have to do this nonsense writing a bunch of multiple strokes all the time. OK this is Zen. This is amazing. This is great. So now let's learn how to initialize it. Well and as you know ASLEF is a typesafe language. So when it comes to type you want to make sure defined type very well. So we learn and we covered that in less one right. So there are two ways to initialize it to find a type where the first way is really no. You can infer based on the value if you've guessed correctly just like the infer based on the value. So when you put the number one through for five there is those are eight. So the TE anything becomes it automatically because while when you push something when you initialize it you are able to 1 3 or 5 and members. Here we go. Anything becomes int. OK. But the second way is you can but you can also explicitly defined a type of tea or anything like this called LEOD generic family. And then we have a generic fem and that's similar to what we did with the function. You have to put this diamond sign right there to show that this is a generic struct and you can see it right there Bill and generic family dog a pen. If you see push you can only enter what you can only enter in value so you can enter 10 like the so you can initialize it with by letting the hey this is this must be. Or you can also just simply tell hey this must be this must be in value. You have to use voire for cons for two in order to make a change. You're right there. So you again make sure when you're working with generic code you definitely have defined a type T. OK let's replace it with t make it more professional and more in just readable. This is a convention we all want to follow convention instead of being unique. So. So we have a lot of time. We can also make extension to generic code. If you don't know what extension is well you can wait for me later in the little chap with the you begin to talk about extensions later less 10. But if you don't know what extension is well you can just skip this part so that you can make extension to the generic generic film. OK. So what do you want to do you want to get the first value first. What do you want to do is you want to get the first recall that first element from generic family so all you get to do is let's call and var first element and this could be an optional type because sometimes you may not have the features you try to get the first element of Derek. Derek family right now at this point right you're not going to have that value. So let's make an optional type. So it's going to T. And also it's going to be a used computer property if we don't know what computer property is. Well just you can simply skip it and wait for next chapter. But I just want to show you what you can do with this. You can see if members DOD is empty. Neal and else return members and zero. If you don't know computer property extension door about it on the walk through. You don't have to know at this point. Just wanted to share what Dierich can do with this. So now you have the ability to code generic family at this. Or are you going to use that property on the top and you can you have this first element property that are available right there and it's going to be for all these small type on the right side should be 10 km or 10. OK. It's going to be an awful time. So you have to unwrap it. Something like that. So I just want to show you what you can do with generic extension. And then lastly I mentioned that you can enter. You can work with any type subject and conditionally based on the requirement that you define. Well to talk about this very briefly how you can actually call that type constraint with generics will tie the salomé scary but what's happening is sometimes you only work with this function that is drugs that allow you to work with any type and you can put like numbers and it doesn't really matter what you put. But sometimes you want to limit what you can work with people. For example when you make a function you want want to work with certain type. So I'm not going to create this low class cake. LOL means laugh out of right. You guys all know right. And now we have a baby. That hurts him LOL. Ok I'm just an example to demonstrate what he can do what it means by type constraints. So I'm going to create a function call just a function that does nothing create low class only t re write is identical to the first example we did. But now if you do a low class you can literally enter anything you can enter like wanted to you can enter string doesn't really matter but sometimes what you want to only limit what the function can work with. So the only thing you have to do is put a device like that and then call it law right there. So what's happening is this add low class Onii can only work with type whose t is low. So for example you can only work with low light. This Yeah. Or if you want to be more clear you do let my my my friend let example lol. OK. And then you can only answer array as an example like the kink so you're not. And if you try to add something else for example if you try to add lower class only if you try and are like one two three four five. And of course right now the T does not t's not say T does not expect element of type. LOL So you're not allowed to enter in. You have to enter something has to be low. OK we call this type constraint for functions and struts. Also just wanted to show you something interesting. You can also add if a little classic and also add the baby like this baby. Just like the OR EVEN DO ask you to enter. LOL Because baby lol It hurts from law. What it does is automatically upcast it for you. So what they do is something like this behind is behind scene is something is something like this is happening way now. But you don't have to put the link but it has its automap outcasted for you and then you're able to work with us. OK we'll see you as leader. Now you understand how to maintain yourself dry by applying generic functions and structures. Do you wish to review the generic syntax. Feel free to check out the article I posted in the lecture notes. Or you may also re watch this video many times in the next. Less and less learned how to provide a shortcut for calling methods with an object. Let's find out.