Generics in Swift: Protocols with associated types

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Great video! It pairs well with my favorite article on this subject–A Protocol-Oriented Approach to Associated Types and Self Requirements in Swift by Khawer Khaliq

👍︎︎ 6 👤︎︎ u/rsobol 📅︎︎ Apr 03 2021 🗫︎ replies
Captions
hello guys welcome to another video let's keep talking about generics and in this video we will talk about protocols with associated types and also we will answer how to use this kind of protocols especially when you see this error in the screen let's work on that my name is pete and this this is swift [Music] tips a previous video we talked about uibu representable and we talked that this particular thing is a protocol conforming view but also containing something called associated type this probably was confusing for you but don't worry today we will explain in detail why we need associated type how to build them let's start alright let's answer first what are associated types well basically the definition says that are placeholder names under or protocols it's kind of another way to use generics but for protocols you could see associated types as a way to specify that that should be a type of any concrete type but we don't care about that the type conforming the protocol will care however let's see first how to build a generic protocol is that possible in swift let's see it let's bring back our classic protocol stack just because it's really easy to use to show you all the functionalities related to this we will use count push and pop okay pretty nice we have a protocol stack but is only working with ins let's transform this in a generic then whoa what happened yeah this is not possible in swift you cannot create a generic like a concrete type this is not possible for protocols so as the error is suggesting we need to use an associated type it's really easy let's fix this what we are going to do is actually use a keyword associated type and then we will specify the placeholder type like you did it with your generics in the type parameter with the brackets it's basically the same so let's use associated type call element we don't know nothing about this type this is a placeholder again and the concrete type will do the rest for us then the only thing we need to do is replace element in the actual int values because we want this to be a generic and that's it pretty forward let's try this and create a stack of ins once we are confirming the stack we receive this error from xcode so let's use the fix button as you already saw in other videos we got this type alias in this case making reference to this associated type element so the thing here is just fill what is the concrete type in order to swift understand how to fill this type and this one so let's use int in this case there you go and now let's fix this issue again this will bring us the required methods for the protocol there you go now let's create a private array just to store the content of this stack and fill the operations let's implement push first it's real simple it's just values dot append and then pass the value in this case element there you go now with bob it's also really simple it's just values that pop last now one really cool thing about associated types is that is it just a kind of clue that swift needs in order to fill the pieces to compile this what i mean is that we need to provide a concrete type here right because swift is asking us okay what is the type of element i don't know nothing in this case we are specifying that is end okay so once we receive the other error message and the fix button xcode is autocompleting the address of code because we already know that we are talking about int because this element is replaced with this associated type but if we actually remove this it's still working yeah we cannot see any error this is happening because swift is inferring that in this case since that the declaration of this is talking about element and we are using int here and here then swift can figure out that element is a need this is pretty cool right so yeah let me show you something i will declare a float here and we got an error because yeah element is having two types at this point so yeah so if it's asking okay what is the actual type is float or it's in but if we specify that is int yeah the h is gone everything fit the requirement this is awesome this is the power of generics and power of type interference in swift finally let's just try it out let's insert some elements let's insert one two three oh yeah we forgot that count is not properly working because it's a read-only value and a computer property in this case so let's return the values that count there you go now let's continue pretty cool we have now our three numbers in the stack we saw previously that we cannot create a generic protocol in the way like a concrete type but is it possible to create a generic type using a protocol with an associated type actually yes let's see that in action let's create a generic type of or into stack but in this case instead of just in we will use any type and we will confirm a stack protocol let's see that in action first we are confirming stack and then we receive again the error from xcode let's fix it and again we need to provide to swift what is the actual meaning of element in this case let's use a generic type so let's put this in bracket and put something like item because i don't want to you know confuse with element then we just need to say okay for this particular concrete type i want to use my placeholder type item as the element for the stack and that's it now let's fix this there you go xcode is autocompleting the element type with item which is great so again we don't need this anymore and we can again fill everything but now using generics let's bring back our private array of values in this case of course let's use item as a type let's use values dot append and insert the element and then use barrio pop last and remember to set this count value and return values.com pretty cool now we have our stack but now using a generic type and a protocol with an associated type this is awesome this combination could become so convenient because in real life we need to use all the tools that swift provide to us to make great apps so yeah this is awesome so let's try this now that we have any possibility with any type to fill here let's create two types of arrays one for ins and one for strings remember to specify the concrete type in the declaration in this case int and now let's use a stack of strings as you can see we have the three elements in here let's see now string there you go we have hello world everybody awesome like generics we can work with extensions and since that we are talking about protocols of course we can use an extension to confirm a protocol but in this case lexus 10 array and confirm array to stack protocol let's see what happened alright so let's fix this issue there you go okay couple of things just happened here one of them is that this time we didn't require to set up type alias with element why well if we go back here in the previous video i told you that it's really important to specify the type parameter name in this case is element and if you remember we just named the associated type with element okay so in other words swiff is inferring that okay both types are basically talking each other so the element from array is inferred has the same element from the stack this is really convenient because as you notice here we already just need to specify push and pop which are the only methods that we need to implement here because we we don't know nothing about this information but the rest is already done also count since that we have count in array and it's basically the same requirement from stack we are good to go we don't need to do anything if someone transformed your array into a stack or used your array as a stack you don't have to worry about it it's just implement push and pop and that's it the rest is completely understandable for swift this is awesome let's then complete this implementation let's use self that happened and then element and then let's do the same with array for pop self.poppery poplar sorry yeah this is awesome so yeah that's why in the previous video i mentioned that is really important this name is not arbitrary so yeah you can use whatever you want but if you try to follow some uh guidance about you know naming element or rapper or in just a few small cases name it with t or you are you know just a letter but in general is much better for you to name it properly like this case pretty cool right at the end of the last episode we saw an issue a really common issue that most developers in swift don't understand or well not much but a lot of them which is this one you know try to use a protocol as a regular protocol when it's talking about a protocol with an associated type there is a big difference here when you use a protocol regularly you can use it as a type but in this case it's not possible to use it right away like this example because you already have an associated type element in this particular example so you need to inform to swift what is that element swift cannot infer that for you there is not enough information for that and for that reason you cannot use it explicitly as a type however you can like the suggestion use this as a generic constraint so if you remember also in the last episode about type constraint you can specify some rules or to subset your types instead of using all the universe of types you can just set a very specific subset and then work with that inside your code that's the idea with protocols with associated type are a special protocols so to fix this really simple is just using again as a constraint so let's create a new placeholder type here called you know structure oh you know let's call it container because you know a stack is a container so and then here specify that container is actually well we need to constrain this to stack only and then we can use this container type here and rename this because well to give more sense to this when you have protocols with associated type this is the right way to use it that's the same case for views in swift ui you cannot declare a view or a type with a view protocol immediately you need to specify view as a constraint in a generic context think about that when you use this kind of things so what do you think about protocols with associated types let me know in the comments i would like to know your opinion and how to use those tools in your development that's it for this video but in the next one we'll finish a class for now the topic about generics and we will talk about where clause because it's something really important especially if you combine generics and protocols with associated types if this video was useful for you don't forget to leave your like and subscribe for more content every week that's it for me thank you so much and have a great day
Info
Channel: Swift and Tips
Views: 2,428
Rating: undefined out of 5
Keywords: swift and tips, swift && tips, protocols, swift, swift language, associated types, associatedtype, typealias, extension, Array, Stack, push, pop, Generics, mutating function, type inference, Protocol can only be used as a generic constraint, associated type requirements
Id: pp4hKZBBci4
Channel Id: undefined
Length: 15min 37sec (937 seconds)
Published: Sat Apr 03 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.