Opaque Type vs Protocol in Swift | Associated Type | Generics | iOS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome to my channel i code i am pallav and today we are going to talk about opaque types associated types generics and protocols these four things are very relatable with each other yet they are very distinct and they form some really good interview questions as well so in interviews when interviewers ask about opaque type associated types i mean that when they ask that what is opaque type a perfect answer comes but when they ask about why do we use opaque type or when they start digging in when they start questioning between the differences of associated type protocols or when they start confusing by linking these things from protocols to generics generics to associated types associated types to opaque types the real problem starts so today in this video we will understand these things in such a way that you won't get confused ever again we won't invest much time on protocol generics or associated types because they are comparatively easy to understand but will look opaque type in depth because that is the pain point for most of the candidates also protocols associated types and generics are important to understand opaque types so we'll just have a glance at them but we won't go in much detail so let's get started let's start with the easiest one first that is generics generics is a way to write flexible and reusable piece of code a code that can work with any type so when you write a generic function you do not mention the concrete type you just put a placeholder t and the t is treated as any type that will be passed by the caller function so the caller function decides the type and the function's implementation is unaware of it instead the implementation is in such a way that it works with any type here's an example from the swift documentation of generics this function that is swapped to values it can swap the values of any type that will be passed read integer bit string float cg float any of your custom types it will just swap the values of the variables because it is written in a generic manner the t denotes the time that will be passed by the caller function and then the function will swap the values irrespective of the type that is passed so this is an easy implementation of generics just to understand it but generics can do a lot more and there can be a lot more components apart from this t so when there will be multiple parameters there will be multiple placeholders for example d u or anything else when there will be a need of putting the constraint on the type there will be type constraints there can be where clause and there can be a hell lot of things which can be used with generics to achieve one final goal that is writing a reusable piece of code it's needless to mention that generix is in the core of swift and almost all the data types of swift have been written in the generic manner bead array b dictionary or even your views all of them are using generics under the hood so generics is really important but the point is that why are we discussing generics when we want to understand the opaque types and all those confusing things it is because generics is exactly reverse of opaque types so if we'll be having an idea of generics understanding opaque types will be comparatively easier so that was about generics and now let's move on to the next bit that is associated types associated types are used with the protocols when we want to make the protocol more generic now by the word generic i do not want you to get confused with the genetics thing that we just discussed what i mean is that when we want to make the protocol more flexible when we want that the protocol should not depend on any type we use the associated types so essentially what we do is that we use the keyword associated type and just mention a placeholder now that placeholder is not the actual type it is not the concrete one it is just a placeholder the entity who will be confirming to this protocol who will be adopting to this protocol they will mention the type and according to that type the implementation will work so irrespective of the type our protocol will work with any type for example you can consider the implementation of a stack and by implementation i want you to think of a protocol a protocol in which you mentioned the functionality that the stack should be having let's say push pop and those functions and the type of the item that this stack will be having it will be decided by the user so whoever will be implementing this protocol for the implementation of stack they will mention the type so regardless of the type it will work for a string it will work for integer it will work for any other type you have just mentioned the associated types that this particular protocol these methods mentioned in the protocol will work for a specific type that has been mentioned as an associated time now the type will depend on the confirmation will depend on the adoption of this particular protocol so whoever entity which is conforming to this protocol will decide the type the type can have certain type constraints so you can define the conditions that this protocol will work for this associated type provided that this time conforms to some other protocol say xyz or you can even mention the where conditions in that but this is how we can use the associated types and because i don't want to go into the details of associated type i will put a link in the description that will be for the avendell lee's article on associated types he has covered the associated type brilliantly and has also explained a problem that is solved using the associated types so i will put the link of that article in the description please go through it if you are not very comfortable with the associated types and get a hang of it but again i would like to make it very clear that do not confuse associated types with the generics or do not confuse protocols with the generics if you want to understand that what is the power of protocols or where you should use them here's the link to one of my videos that i did on inheritance versus interfaces and there i explained the protocols in depth in detail have a look at it so this was about associated types and now the point comes that why did we try it understanding it and the answer is same that because the opaque types are very closely related with associated types opaque types is something that solves a problem which is created by associated types let's look at it opaque type is used when we want to hide the information of the type that is being returned from a function now let's break it let's understand it slowly so first of all the word opaque object itself means that you cannot see through it so when we want to remove the transparency related to the type when we want to hide something when we want to hide the return type we are using the opaque type now what do i mean by hiding the type so function is returning something about which the caller function is not aware of what i mean is that the protocol type is being returned instead of the concrete type while under the hood a concrete type is being returned so from that particular function a concrete type is being returned but the color function gets the protocol type as the return now this creates a lot of confusion so what do i mean when i say that a protocol type is being returned from a function yet protocols and opaque types are two different ends because in the first look it appears that these two are exactly same things when i'm saying that a function is returning a protocol it means that it is returning a protocol now what does an opaque type means and why is it being used what is the problem it is solving and all these questions are very easy to answer when we take a use case when we take an example understanding the whole concept with just theory is really difficult it is difficult to explain and it is difficult to understand as well so let us take an example and then we will come across a problem which will be solved through opaque types let's go for it let's understand our use case first assume that i am working on an application related to the banking sector and i need to write a function which would return a boolean the boolean will be for deciding that whether the user is eligible for the loan or not now the business logic that i will be writing here is that i will be checking the credit limit available on the credit card of the user versus the credit limit of any card which allows that loan now i understand that this logic is a complete and this is not how it works in the banking domain in the banking sector and i have no idea of how the loan approval works this is just an example for showing the opaque types that how opic types comes to rescue when it comes to the problems related to the associated types so for this i'll need multiple entities for example cards credit cards visa master those things some protocol may be some associated type maybe so let's start writing them the very first thing that we need for implementing this is an entity called card and for card i would like to create a protocol because that protocol will be confirmed by different type of cards maybe mastercards visa cards or any other card so let's create the card protocol first now there are certain things which each card should have for example the type of the card like gold platinum or those kind of things then limit of the card what kind of credit limit that card is having number for the card and few other things so let's start implementing them now instead of taking the card number as normal string i would like to take it as an associated type and that associated type should be confirming to a protocol let's say card number protocol because credit card numbers are not the normal numbers they have a certain logic related to the bin of them so let's not go into those details of deciding the bin but at least what we can do here is that we can make a protocol for let's say card number protocol and instead of taking the number as a string we can take it as an associated type which should confirm to our card number protocol and let's put a function for validating the card numbers and because we have mentioned these properties within the protocols we need to add get or set with them so till now we have a protocol for cards and that protocol is having certain properties like type limit also we are having a property number which we have declared as an associated type now the property card number it will be decided by the entity who will be confirming to our protocol card so they can use any type for the card number as far as it is confirming to the protocol that is card number protocol because we have mentioned that the card number our associated time should be of type card number protocol over here now let's create two structs for visa card and mastercard which will be confirming to our protocol card let's create one more struct for mastercard now that we are having two types that is visa card and mastercard and both of them are having different credit limits let's try writing our function that we talked about that was our business logic let's try writing it now this function requires two cards one of the user and one for the card against which the limit will be compared so for that we can have two functions assume that these two functions that is get user card and get loan eligibility card these two functions are being written by some another team and that team do not wants to disclose the type of the card that whether it is a visa card or mastercard so what they are doing is that they are returning the card the protocol type from this method because in this method that is get loan eligibility the type of card is not important because what i need to do is i need to compare the limits so what i can do here is that i can call the method that is get user card dot limit if it is greater than equal to get loan eligibility card dot limit so in this method that is get loan eligibility i do not need the type of the card or i do not need to know the concrete type of the card and that is why that team who has implemented these two functions that is get user card and get loan eligibility card they are not disclosing the concrete type that whether they are returning the mastercard or visa card they are just saying that they are returning something which is confirming to the protocol card which is completely fine on their part now let's understand that why are we getting these errors over here so the error says that protocol card can only be used as a generic constraint because it has self or associated type requirements which is true that our card protocol it is having this associated type that is card number so whenever we have an associated type in our protocol we cannot return it as a type this is because when we return protocol as a type compiler does not keep a track of the concrete type of the exact type that is being returned instead it just takes the protocol as a type and because we are having the association of a type of a particular type that has been passed by user for this protocol that is card number because we mentioned it as associated type so because we are having this involvement of an associated type here compiler wants to keep a track of the exact type which is being returned and that is why this error is here so what we need to do here is that we need to find out some way through which the compiler can track the exact type that is being written and swift has introduced the keyword sum through which compiler will get to know about the exact type that is being returned and that is what we call as opaque type so here before the card if i write the keyword sum we will see that the errors will be gone so now we can say that these two methods that is get user card and get loan eligibility card these two methods are returning an opaque type it is because the caller function that is get loan eligibility it is not aware about the type that a mastercard is being returned from this method or a visa card is being written from this method what this method is getting to know is that some card is being returned while the compiler is aware about the exact type that is being returned so that is where opec types comes to rescue so when you want to use associated types with the protocols but you do not want to reveal you do not want to disclose the concrete type that is being returned from a function you can use the some keyword and you can return an opaque type from that this is being exhaustively used by swift ui in swift ui you must have seen that your computed property that is body it is returning some view from it now we eat a v stack beat and h stack or b it any other custom view some view is being returned by the computer property body and that is where we say that an opaque type is being returned so in brief we can understand opaque type as a type about which the caller function is not aware of but the function's implementation knows that which type is being written now this is exactly reverse of the generics so in generics the caller function decides the type and the function itself is not aware of the type that is being received as a parameter while an opaque type the function's implementation is deciding the type that what is to be returned while the caller function is getting just a protocol type as the return type and it is not getting to know the actual type that is being returned the concrete type that is being returned so when we do not want to disclose the type information be it while writing frameworks or sdks we can use the opaque types moreover opaque types can be used when you are using associated types in your protocols i understand that i have not discussed associated types too much in this video but that is because it was not the purpose of the video if you want to know more about associated types i'll be mentioning the link of the avendell lee's article in the description please go through it it's a really good one the point is that when you are using associated types with the protocols and then you want to return protocol as the written type you will have to use the sum keyword to make it as an opaque type and then the compiler won't throw the errors i hope that you would have got a gist of what opaque type is and how it is different from protocols how it is different from generics associated types and all these things and once you start using them once you will intentionally include them in your code you will get the hang of it and believe me they are very powerful they are very useful especially when you are trying to write a reusable piece of code when you are trying to write frameworks sdks and all those things where you want to hide the type information where you want to keep your types as private or internal opaque types is something that you will be using exhaustively so get a hang of it try using it and if there are some doubts related to this video or whatever we have discussed in this please write them in the comments and i'll try to answer as much as possible that's pretty much for this video a new video comes out every weekend so you can consider subscribing to the channel let's write better code together happy coding and stay safe
Info
Channel: iCode
Views: 2,742
Rating: undefined out of 5
Keywords: iOS, swift, xcode, iCode, pallav, pallav trivedi, opaque types, generics, protocols, associated type, protocol oriented programming, swift 5, reusable code, app development, associated value, enum, extensions in swift, what’s new in swift, Xcode 13, android, mobile app development, iOS interview question
Id: SPhATsEQR74
Channel Id: undefined
Length: 17min 16sec (1036 seconds)
Published: Mon Sep 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.