How to use Lazy in Swift

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're gonna talk about the lazy keyword in Swift I'm gonna talk about what it is how to use it when you should use it and then some of the some of the pitfalls of using it too much but real quick today's video is sponsored by Squarespace Squarespace is an all-in-one platform to get your beautiful online presence or iOS developer portfolio up and running very quickly check them out at squarespace.com slash Shaun Allen alright let's dive into this example but first let's talk about like what lazy is it kind of does what its name says right it it puts off work until you need it or you may hear this called like just-in-time like as soon as you need it it'll get it ready for you and we're gonna do two examples like one common example is you know you're initializing your object and during that initialization you want to have a variable but that variable doesn't know about the other variables yet so you can do that lazily and then another very common example is if something is very computationally heavy like it takes a long time to process then you want to do that lazily because you don't want that to always be going you only want to do that heavy process when you need it and we're gonna dive into some examples so the first example I'm gonna show is during that initialization where I said like an object may not know about the other variables so in this example I want to have an introduction so var intro duction so I want this introduction to say you know someone's always entered the game at this position for this team you know that stuff but the introduction doesn't know about the name team and position yet right because this is going on during initialization so if I mark this lazy of our introduction equals and then you have to do open closed parentheses at the end actually run this closure because essentially you're calling a function here but I want to return now entering the game and then this is going to be the name position and then for thee and then team so for example now entering the game Michael Jordan shooting guard for the Bulls like that's what I want us to say but I want this introduction to be as a property on players so I can just call like player dot introduction and spit out this strength but again the reason we had to make this lazy is because during the initialization right I don't know about name position or team the initialization has to complete before I have that information so now what I can do is I can create a player var Jordan and Jordans going to equal a player and we'll initialize that with a name of Michael Jordan team is the Bulls position is shooting guard and we can get rid of this parameter because it's going to be nil for the initialization so now I can call print Jordan dot introduction so again this is the example when you want a property that requires you know the full initialization before you use it and you can make that lazy to get that so if I go ahead and run this we're gonna see the introduction down here now entering the game Michael Jordan shooting guard for the Bulls now you may be asking yourself why can't this just be a computed property rather than a lazy variable that's fine that would work here too but let's talk about the high computational example and why a computed property wouldn't be good for that because a computed property every time you access this like Jordan introduction it gets recomputed every time but you know for this string no big deal again if this was a very heavy computational function here it would be a big deal and that's what we're gonna do right now all right so let's make some room here get rid of this and let's get rid of this print statement we don't need that anymore but we will need the room and I do have a piece of code that I'm gonna copy and paste over cuz you don't want to watch me type this takes too long I'll walk through okay this is just kind of our expensive function calculator right so it's just a calculator with a static func called calculate games played it returns an int I'm basically just creating a very large array so here's my empty array I'm iterating through that array 4,000 times appending a number to it each time and then I'm returning it games dot last yes I know not very efficient that's the point so now if we scroll down and create a property on player so var games played and that is going to equal calculator dot calculate games played so now every time I initialize a player here right where Jordan gets initialized it's going to run this super long function now watch up here on the right next to this for loop you're gonna see it iterate four thousand times you can see how long it takes because it's an expensive function and it's being called when we're initializing this player down here called Jordan right because games played runs and this is going to you're gonna see power of lazy here all right let's run this and you can see it counting up to 4,000 it takes a bit right there goes 4000 now our players initialize so you can see how long that took so what we want to do is we don't want to calculate that during the initialization we want to calculate that lazily so we only want to do that calculation that takes 4 seconds when we need it right if we're not going to access player dot games played there's no point in spending those 4 seconds to calculate that so let's make this a lazy var just like our introduction below we'll put a space here so people can see that and then that that and then return and give the open and closed parens to actually run the function so now when we initialize our player watch up top again where that 4,000 counted it's not going to count the 4,000 and our player is gonna be immediately initialized down below so it's running okay it ran nothing happened we didn't run that calculator function but our player down here on the right has been initialized and that's the power here of doing it lazily now let's actually access it so you can see it so we want to print Jordan dot games played so now we're actually accessing it and then that's when it's going to actually you know run so if we run it again it's running up there in the upper right you can see because we are actually accessing it down here on line 27 and we printed it out down here in the console as you can see now again back to that computed property right because the computer property kind of does the same thing right you're it's not going to compute games played until you actually access it but the difference with lazy is lazy actually stores that value right so we got that value of 4,000 for games played now anytime I access games played it's not going to do that calculation it's stored it on the object however if this was a computed property where you would just do var games played equals and then you're gonna get rid of this get rid of that look get rid of equals this is of type int there we go so now this is a computed property right here now if I do we're just gonna copy and paste this a couple times so if I were to access Jordan dot games played every time I try to access it it's gonna run that calculation again so we'll run it up here and I'll watch this number up here you know we're gonna go to 4,000 we're gonna go right past that to 8,000 and then on to 12,000 right there we go see 4,000 we're doing a 7000 so now you're delaying you know three times as long but that's the computed property the computer property is going to run the calculation every time you try to access it we're as lazy AK calculates it once and then stores it on to our player object and lazy really comes in handy when you're creating like multiple objects like say we wanted to you know create a whole starting five here well let's take this back to of our games played equals our calculator equal you know calculate games played so now this is just the typical variable we had before where it's gonna run during initialization and again I copied and pasted this but let's say we have a whole new starting five for the Bulls here right the 97 Bulls starting five so we're gonna initialize five player objects and you know what's gonna happen right if you don't make this a lazy variable when I run this this is gonna go nuts up here right it's gonna run five times or 20,000 times it's gonna take forever because it's initializing five player objects down here and it's gonna do the calculation five times so a beautiful example here of where lazy is going to save you that and it's only gonna run the calculation if I were to do like Rodman gangs played now let's talk about the main pitfall of using lazy right because it kind of sounds too good to be true just in time why not make everything lazy that way you're getting everything just as you need it well here's the main pitfall here in the documentation and I'll link to this in the description if you want to read more about these lazy stored properties you scroll down here and you can see that they're not thread safe basically we read this real quick if a property marked with lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized there's no guarantee that the property will be initialized only once so again if we're using a lot of multi-threaded code it can be accessed by multiple threads so you could get some funky behavior so that is the reason why you wouldn't want to just overuse lazy so again use it sparingly for situations like this when you have a heavy calculation that you don't want to run until you absolutely need it but lazy is perfect for that now if you're here learning about lazy the major an iOS developer maybe you're looking for a job or that next contract and for that a portfolio is very helpful and that brings me to today's sponsor Squarespace Squarespace is a great way to get that online presence that portfolio up and running extremely quickly and look like war i OS developers we're not front-end web development birds that can quickly create a website make it look good for every browser type all the different screen sizes make it responsive like there's a lot of work that goes into creating a website and as iOS developers I think we'd rather spend our time like building apps learning new things about Swift or the Apple platform so I'm of the mind let's something like Squarespace take that portfolio off your plate and you can have something beautiful again up and running pretty quickly they got great themes they handle all the analytics all the SEO stuff for you it's gonna look great and it's simple to use and the portfolio is gonna be insanely valuable to you so head over to squarespace.com to start your free trial today and when you're ready to launch that portfolio go to Squarespace comm slash Shawn Allen to get 10% off your first purchase of a website or domain so that wraps up this video on the lazy keyword in Swift again we went over two very common examples hopefully you understood that if you have any questions feel free to leave it in the comments we'll see in the next video
Info
Channel: Sean Allen
Views: 24,524
Rating: undefined out of 5
Keywords: Swift, Swift Tutorial, iOS Developer, iOS Development, Swift Code Tutorial, Swift app tutorial, swift lazy var, Sean allen, swift lazy, swift lazy loading, lazy swift, lazy loading swift, lazy property swift, lazy variable swift, swift lazy property, swift keyword, lazy in swift, lazy loading in swift, lazy var in swift
Id: xKoua1Mi6qE
Channel Id: undefined
Length: 9min 56sec (596 seconds)
Published: Thu Feb 27 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.