How to use opaque return types – Swift for Complete Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] swift provides one really obscure really complex but really important feature called opaque return types that help us reduce complexity in our code now honestly i would not include these in a beginner's course if it weren't for one simple fact the very first swift ui code you'll see in xcode uses opaque return types every sift dy code uses it it's really important now pro tip voice start you don't have to understand how these things actually work what matters is you know what they mean and roughly what they do now as you're following along you might be thinking to yourself is it really useful please trust me please stick with it it is useful try to power through you will see it from second one into 50y it's that common okay disclaimer out of the way let's implement two simple functions first one get random number returns int between one and six and then get random ball which returns bulldog random now ball at random returns either true or false randomly unlike uh integers and decimals we haven't got to specify any parameters here it's only true or false that's what it does now both int and bull conform to a common swift protocol called equatable which means these things can be compared for equality is three equal to three is five equal to nine and so forth and the equatable protocol is what allows us to use equals equals to compare two instances of the same type like this we could say print get on a number is equal to get random number which is true or false it's random right now again both inch and bull conform to equatable and as a result we could try amending our function to return an equatable value like this returns equatable in both those places however that code will not work and swift will throw up an error that is deeply unhelpful at this point in your swift career it'll say protocol equatable can only be used as a generic constraint because it has self or associated type requirements what swift error means is uh returning equatable does not make sense and understanding why it doesn't make sense is the key to understanding opaque return types first up easy bit yes you can return protocols from functions of course you can in fact often it's a helpful thing to do for example you might have some function that finds car rentals for users it'll ask questions like well how many passengers do you have how much luggage do you have and based on the input you're working with it'll send back a return type maybe a compact be an suv maybe a minivan depending on your requirements that's what i can do return the exact types of struct for example now in this case it returned three kinds of things compact suv or minivan and so we don't want to have three different functions we want to return a protocol some kind of vehicle that is uh conforming to by all those structs the protocol as we have a cause of function will get back some kind of car that matches their request here's the the right car for you which might be a minivan an suv a compact a sedan or who knows what right without us having to write ten different functions for all possible car varieties now each of these things will implement all the same methods and properties as required by our vehicle protocol which means they are interchangeable from a coding perspective we don't really care which one we get back i'd like to support you know fit people five or add luggage three large whatever i know the basic things vehicles are required now think about incs and bulls yes they both conform to equatable we can compare five to five and true to false and so forth but they aren't interchangeable we can't say print five is equal to true swift will not let us do that regardless of what protocols they conform to now returning a protocol is useful because it lets us hide information we can say rather than get an exact kind of car back it returns an suv instead we focus on functionality these are the things we need it might say report back the number of seats it has or how much fuel it uses or how much it costs those are things we care about when it comes to the kind of card inside there and it means we're keeping the flexibility inside our code we can later on say you know actually um i want to add some more types here i want to add a a race car or a pickup truck as return types inside my function because ultimately the return type is a vehicle doesn't matter as long as those new types can form the vehicle you can return them so hide hiding information in this way is really useful but it's just not possible with equatable because it makes no sense you cannot have one equatable and another equatable and use equals equals even if we call get random number twice to get two integers we still can't compare them because we've hidden their type we've discarded the fact that integers swift just goes ah they're equatable could be any kind of equatable so i can't compare them this is where opaque return types arrive on the scene they let us hide information in our code but not from the swift compiler i'll explain this means we can return a new type in the future you know i'm bored of suvs return minivans now i'm boarding minivans return sports cars whatever we reserve the right to keep our code flexible internally what we send back can change but swift internally the compiler looks at the code and says okay it always sends back a truck or sends back an suv or whatever it understands the actual type of data being sent back so we hide it for flexibility so we can change our minds later without breaking the rest of our code but swift knows what's up it knows what's really going back and let's have a go at using these to upgrade our functions you have tweets already no one tweets for you you're not hungry at all you're telling lies anyway let's upgrade our functions to support this we're going to say get random number returns sum equatable and random ball returns some equatable like that we're saying it'll be equatable but it'll be some specific kind of equatable in this case swift can see it'll be an integer really and with that in place we can now run our code the answer's false we had two random numbers made and they did not match but it understands behind the scenes it'll send back an equatable value that happens to be an integer now from our perspective we still have an equatable if i call get random number you'll see i get back an equatable it says in the in the cochlea the bottom there in in purple equatable if i do let num equals get random number and then look at num inside here you'll see it's equatable but swift knows what it really is behind the scenes swift knows it's actually an integer so it can be compared with other integers now returning an opaque return type like this means we still get to focus on the functionality we want it's some kind of vehicle for example which in turn allows to change our mind later on to say okay let's no longer do in dot random let's do double dot random right and now it's it's still fine that's still allowed it'll now be a double going back still equatable swift's still happy we can change our mind freely and the code works great i'm going to change the whole rest of our code to gone from into double what you would have done if we'd been explicit if i had return type int here everywhere this function was called would say i expect an integer here why give me a double so cell creatable allows to change our mind later but the real advantage here the real power thing is that swift always knows the actual type of data going back he understands what it really is it is a a subtle distinction but if we return a vehicle a straight protocol returns vehicle it means any sort of type that conforms to the vehicle protocol but we don't know what car sedan truck minivan whatever right whereas returning some vehicle or some equatable or whatever means a specific sort of vehicle type but we don't want to say which one we want to keep our options open at this point i feel basically certain your head is spinning so when i give you a real example of why this is so heavily used in swift ui swifty y needs to know exactly what kind of layout you want to have in your code what you want to show on the screen and so it's our job to right clearly describe it so in english we might say uh there's a screen and a toolbar at the top a tab bar at the bottom and in the middle is a big scrolling grid of color icons each of which has a label below uh saying what the icon means written in a bold font and we tap it a message appears we just describe our layout and obviously not in english but in swift when swift ui asks for our layout that description the the whole paragraph of english text becomes the return type for our layout it returns exactly that there is a navigation bar tab scrolling grid is our turn type and so you've got to be explicit about every single thing you want to appear exactly describing every single thing you want to appear including positions colors font sizes and more could you imagine typing that as a return type it'll be vicious it'll be impossible to understand it would be bluntly a mile long and worse every time you change your layout your code you have to change the return type to match this is where opaque return types come to the rescue swift has a protocol called view like this and view is brilliant because it's used for some kind of thing we want to appear on the screen buttons images text and more are all views as our shapes circles squares rounded rect and so forth they're all views and so when it comes to describing what our layout returns we say some kind of view some view we don't want to say what it is we want to keep our options open but swift internally can say aha there's a tab bar a navigation bar and a scrolling video to do a swift knows exactly what's being returned even though we haven't had to specify ourselves and therefore swift will use that to create the correct layout for us now like i said at the beginning they are very honestly obscure feature and they're very complex but they're so critically important to the way swift ui works and i genuinely wouldn't cover them if it weren't for the fact that your very first swift ui app you make the very first swift ui code you see will have some view as the return type so when you see that in your 50 ui code you haven't got to remember exactly what it does or how to make them yada yada all it's doing is saying to swift this is going to send back some kind of view layout stacks of stuff scrolling navigation bars who knows what but i don't want to have to write out the exact thing i want you to figure out for yourself you
Info
Channel: Paul Hudson
Views: 9,264
Rating: undefined out of 5
Keywords:
Id: Fyhm8RxwpKs
Channel Id: undefined
Length: 13min 42sec (822 seconds)
Published: Tue Oct 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.