How to use Lazy in Swift

  Рет қаралды 38,803

Sean Allen

Sean Allen

4 жыл бұрын

Head to squarespace.com/seanallen to save 10% off your first purchase of a website or domain using code SEANALLEN.
In today's video we discuss the Swift keyword, Lazy. I'll tell you what the keyword means, how to use it and when to use it. We'll also discuss a common pitfall of using "lazy" too much in your codebase.
This tutorial was done using Swift 5.1 and Xcode 11.3.
Lazy Documentation:
docs.swift.org/swift-book/Lan...
If you like my teaching style, I've released my first iOS dev course which is all about the take-home project job interview for iOS developers.
Course Info - seanallen.teachable.com/
Link to my book - How I Became an iOS Developer:
gumroad.com/l/sean-allen-origin
Hired.com:
hired.com/x/1n01g
Check out my podcast, iOS Dev Discussions:
itunes.apple.com/us/podcast/i...
Are you a gamer? I'm streaming video games on Twitch:
twitch.tv/seanallen
Book and learning recommendations that help out the channel if you decide to purchase (Affiliate Links):
Ray Wenderlich Books:
store.raywenderlich.com/a/208...
Ray Wenderlich Videos:
store.raywenderlich.com/a/208...
Mark Moeykens SwiftUI Views & Animations Mastery:
www.bigmountainstudio.com/a/f...
Paul Hudson's Hacking With Swift:
gumroad.com/a/762098803
Learn Advanced Swift Here:
gumroad.com/a/656585843
Links to my iOS Dev Setup & iOS Dev Book Recommendations
www.amazon.com/shop/seanallen
Personal Links:
Twitter:
/ seanallen_dev
Instagram:
@seanallen_dev
#swift #softwaredeveloper #iosdeveloper

Пікірлер: 131
@seanallen
@seanallen 4 жыл бұрын
Watch Next - Loops in Swift - kzfaq.info/get/bejne/b7meqpqh1NLHcok.html
@koczkadavid2009
@koczkadavid2009 4 жыл бұрын
Perfectly on point, short and informative, thank you!
@seanallen
@seanallen 4 жыл бұрын
Happy to help, David 😀
@KimbrellBrad
@KimbrellBrad 3 жыл бұрын
First time I've heard it explained that way and it clicked! Sean, thank you for what you do for the community!
@homedudycz941
@homedudycz941 4 жыл бұрын
Small things in your example: 1. You have made all properties in struct variables (var), so you could change them, and introduction would not update, so in this example it would make more sense to make them let. 2. When you only create a simple values for lazy var, like here, you don't actually always need to close them in the closure - only when there is more then one line of code to return them. You could just do lazy var introduction = "Hello \(name)"
@seanallen
@seanallen 4 жыл бұрын
Good points 👍
@brandonfong9998
@brandonfong9998 4 жыл бұрын
sean allen, thank you! i just landed my first ios dev job after self learning for about a year. your videos have helped me tremendously!! (especially the interview series)
@seanallen
@seanallen 4 жыл бұрын
Congrats, Brandon! 🎉🚀 Happy to hear I could be of some help. Best of luck in the new job!
@mutasemwahbeh6954
@mutasemwahbeh6954 3 жыл бұрын
Thank you for this powerful comparison between computed properties and lazy and lazy now become so clear to me 🔥
@nileshjdarji
@nileshjdarji 2 жыл бұрын
One of the best explanations on Lazy out there. I keep coming back to this video to re-educate myself if I forget what lazy does. Thanks for this great example.
@KFrench1123
@KFrench1123 4 жыл бұрын
Great explanation Sean! "lazy" is something I don't feel like I see that much in code but it definitely comes up and is worth knowing so I am glad to have this video as a review. Thanks!
@seanallen
@seanallen 4 жыл бұрын
Glad you enjoyed it, Kevin 👍
@andonidasilvaotero9652
@andonidasilvaotero9652 4 жыл бұрын
Now I am able to see the difference between lazy and computed property!!
@seanallen
@seanallen 4 жыл бұрын
Happy to help with that, Andoni 👍
@piyushgeorge1847
@piyushgeorge1847 4 жыл бұрын
Very well explained👍🏻👍🏻. Great video as always. Thanks Sean.
@seanallen
@seanallen 4 жыл бұрын
Glad you liked it, Piyush 👍
@ryankanno2562
@ryankanno2562 3 жыл бұрын
Awesome explanation and example! Keep up the great work!
@dziobaczy
@dziobaczy 4 жыл бұрын
Neat explanation Sean! I would just add a few words, about lazy views in controllers, as it’s at least imo nc approach as it grants access to other views and properrties in closure initialisation proces.
@szymonrybczak
@szymonrybczak 4 жыл бұрын
Very helpful video! Thanks!
@seanallen
@seanallen 4 жыл бұрын
You're welcome!
@andreagrumpeenlate5813
@andreagrumpeenlate5813 4 жыл бұрын
Sean this was excellent.
@seanallen
@seanallen 4 жыл бұрын
Happy to hear that you enjoyed it, Andrea 😀
@Stricken174
@Stricken174 4 ай бұрын
Very interesting mention about multithreading. Thank you Sean, as always.
@seanallen
@seanallen 4 ай бұрын
Happy to help!
@gakkieNL
@gakkieNL 4 жыл бұрын
Good topic and well explained! I enjoyed it, Thanks!
@seanallen
@seanallen 4 жыл бұрын
Thanks Gakkie!
@barclaysd
@barclaysd 4 жыл бұрын
Awesome video - really well explained! Thank you!
@seanallen
@seanallen 4 жыл бұрын
Glad you liked it, Daniel!
@mohdrahib7006
@mohdrahib7006 3 жыл бұрын
very nice explanation 👍🏻
@kevinbenavides92
@kevinbenavides92 4 жыл бұрын
Great explanation, simple and effective examples. Thank you so much.
@seanallen
@seanallen 4 жыл бұрын
Glad you enjoyed it!
@piyush1695
@piyush1695 4 жыл бұрын
Great video just precise to the point and perfectly explained.👍
@seanallen
@seanallen 4 жыл бұрын
Glad it was helpful!
@MarvelousLXVII
@MarvelousLXVII 4 жыл бұрын
Great tutorial as usual.
@donathmm3881
@donathmm3881 4 жыл бұрын
Great video dude! Finally understood it
@seanallen
@seanallen 4 жыл бұрын
Happy to help, Donat 😀
@karlkaiser3166
@karlkaiser3166 4 жыл бұрын
Hey I really hope you read this. This video helped me so much, I love you!!
@seanallen
@seanallen 4 жыл бұрын
Happy to help, Karl!
@MrMarchsb16
@MrMarchsb16 4 жыл бұрын
thanks @Sean. On point as always
@seanallen
@seanallen 4 жыл бұрын
Glad you liked it 😀
@amitarya4894
@amitarya4894 10 ай бұрын
thank you so much, explained very well.
@seanallen
@seanallen 10 ай бұрын
Glad it was helpful!
@MpomartMedia
@MpomartMedia 4 жыл бұрын
Hey Sean, many thanks once again for sharing your know how on the subject of LAZY in iOS Development! as always a polished delivery which get to the meat and bone of the subject matter in double quick time. Keep up the good work. Henry
@seanallen
@seanallen 4 жыл бұрын
Thanks Henry 😀
@MpomartMedia
@MpomartMedia 4 жыл бұрын
@@seanallen You are welcome Sean!
@leticiaf.3808
@leticiaf.3808 4 жыл бұрын
Thanks for share this! 🧡
@seanallen
@seanallen 4 жыл бұрын
Happy to help!
@JasonMitchellAZ
@JasonMitchellAZ 4 жыл бұрын
Great comparison of lazy vs computed properties
@apurvajain1203
@apurvajain1203 2 жыл бұрын
Wonderful Explaination
@DatafoxSoftware
@DatafoxSoftware 4 жыл бұрын
Thanks Sean, very useful as all your content.
@seanallen
@seanallen 4 жыл бұрын
Glad you liked it, Datafox 👍
@tuancuong92
@tuancuong92 3 жыл бұрын
Thanks a lot Sean
@seanallen
@seanallen 3 жыл бұрын
Happy to help!
@JugglerMaxx
@JugglerMaxx 4 жыл бұрын
Really well explained!
@seanallen
@seanallen 4 жыл бұрын
Thanks Maxx 👍
@fabioesposito6549
@fabioesposito6549 4 жыл бұрын
yeah max.. The brainwashing is going always as good as a paradise corner
@nirajtiwari8141
@nirajtiwari8141 4 жыл бұрын
Hi Sean, your content is very easy to grasp and digest :) Please make a video on Co-ordinator pattern as I am really confused where to put the navigation responsibility inside a MVVM based app. Keep the great work going
@seanallen
@seanallen 4 жыл бұрын
Glad you liked the videos, Niraj 😀
@libvlog2264
@libvlog2264 4 жыл бұрын
Example is wild tho 🤯🔥
@vamsi3877
@vamsi3877 4 жыл бұрын
this is best explanation i have ever seen . It would be great if you explain why not " lazy let "
@seanallen
@seanallen 4 жыл бұрын
Lazy vars are nil until they receive a value. A "let" cannot be nil.
@erhanbakrc6619
@erhanbakrc6619 4 жыл бұрын
Such a great explanation. Waiting video for "getter and setter" by the way :)
@seanallen
@seanallen 4 жыл бұрын
Glad you liked it, Erhan 😀. I've just added getter and setter to my "keyword to-do list".
@frankfernandez1957
@frankfernandez1957 4 жыл бұрын
Oh wow what a handy functionality. Thank you!!!!
@seanallen
@seanallen 4 жыл бұрын
Glad you liked it, Frank!
@iOSTechie
@iOSTechie 4 жыл бұрын
Thank you Sean
@seanallen
@seanallen 4 жыл бұрын
Happy to help, Prashant 👍
@omrtahmed
@omrtahmed 2 жыл бұрын
Couldn‘t be any better explained
@PaulPeelen
@PaulPeelen 4 жыл бұрын
Good explanation and well done! Clean and easy to follow. One note though, the lazy declaration doesn't have to be written as a computed variable (since you don't _need_ to be running a function). It can be a direct string declaration. Meaning this would be sufficient: lazy var introduction = "Now entering the game: \(name), \(position) for the \(team)" . The { and } are not needed, there is no need for a function unless * magic * needs to be done. A good thing to keep in mind is that as long as the lazy variable is using variables I would recommend using a computed variable instead since the lazy variable can become invalid if the variables are changed. If the lazy variable would be using constants instead I'd say go lazy since "introduction" will always be correct! :)
@seanallen
@seanallen 4 жыл бұрын
Thanks Paul! And great clarifications 😀
@RSzady
@RSzady 4 жыл бұрын
I use lazy generally when creating a class variable in a ViewController and need to access another class property before it's been initialized.
@laurapotter6321
@laurapotter6321 2 жыл бұрын
omg I love this guy
@RahulPahuja1991
@RahulPahuja1991 4 жыл бұрын
Your Videos are Good....
@mohammadelrefaey6345
@mohammadelrefaey6345 3 жыл бұрын
u r great
@thisisphilchan
@thisisphilchan 3 жыл бұрын
aside from the excellent tutorial. i love that you know about the beloved Bulls :)
@seanallen
@seanallen 3 жыл бұрын
Know about out them? I lived it! 😀
@phillipchan1
@phillipchan1 3 жыл бұрын
@@seanallen 🙋🏻‍♂️ born and raised in Chicago :)
@Dgpratt4
@Dgpratt4 4 жыл бұрын
Good stuff! As a note, the closure initializers are not necessary on the lazy properties.
@seanallen
@seanallen 4 жыл бұрын
Thanks for clarifying that, Daniel 😀
@Soh965
@Soh965 3 жыл бұрын
lazy variables are my kind of variables. Doing works only when they are needed.
@willasaskara
@willasaskara 4 жыл бұрын
thankss
@JunaidKhan-ny8tu
@JunaidKhan-ny8tu 4 жыл бұрын
that's super super awesome :-) amazing amazing
@seanallen
@seanallen 4 жыл бұрын
Glad you liked it!
@HintzStefan
@HintzStefan 4 жыл бұрын
You do not need the closure. You can initialise the "lazy var introduction" in one line.
@ruslangarifulin2609
@ruslangarifulin2609 4 жыл бұрын
The explanation is good, and I agree that lazy property is better than computed, but sometimes those properties may be using other properties from class/struct and if those properties change, the lazy property will still give the same value as the first time, while computed property will take the new values into consideration
@seanallen
@seanallen 4 жыл бұрын
Yup. Use the right tool for the right situation.
@sergeimeza4663
@sergeimeza4663 4 жыл бұрын
Pro tip: Use lazy on UI (main thread) at a superclass (let's say AppViewController). That way you will have access to boilerplate components (let's say an alert, an action sheet, or a bar button) when you needed, as you needed available everywhere for free. ;)
@chudq
@chudq 4 жыл бұрын
I noticed an interesting point of lazy property. It is also settable. When you set it to difference value before getter, the lazy block would not execute at all! Or the lazy property can be set to a different value. In order to keep it lazy and immutable, it is better to explicitly specify set private: private (set) lazy value: String = { return "test"}()
@FRAMEDSKATEKREW69
@FRAMEDSKATEKREW69 4 жыл бұрын
didn't notice this was a new video lol I saw the word lazy and I thought it was maybe a video about how to code swift lazy but efficient
@seanallen
@seanallen 4 жыл бұрын
Lol, no... not quite. 😀
@DimitrisTheo
@DimitrisTheo 4 жыл бұрын
Great video! How can we use this in an app?
@alexanderkharevich3936
@alexanderkharevich3936 3 жыл бұрын
You can also use lazy for dependency injection, because you can set it to any value after instance initialization class A { lazy var serviceA: APIService = .init(baseURL: "google.com") } let a = A() a.serviceA = MockAPIService()
@smarter2610
@smarter2610 4 жыл бұрын
sean different question, where to put code in MVC with AlertViewController? In ViewController or different class? Is it ok to put every function in ViewController?
@Shmarti
@Shmarti 4 жыл бұрын
Super
@balashivashankar2225
@balashivashankar2225 4 жыл бұрын
Hi Allen can I have a video of programatical constraints please
@seanallen
@seanallen 4 жыл бұрын
Try this one: kzfaq.info/get/bejne/Z85zqrJ6zNCwcnU.html
@amranmohamed377
@amranmohamed377 2 жыл бұрын
Hi mr sean, thanks for sharing the information and I have some trouble when I’m initializing my jordan instance in your example coz I’m getting error: missing argument for introduction. Btw I’m using swift 4. I just wrote everything as u did and still I’m getting that error. Plz any help
@Tenly2009
@Tenly2009 4 жыл бұрын
Hi Sean... I always wondered exactly how “Lazy” works - and now I know! Thanks! I’m wondering though: Wouldn’t we achieve the same benefits by using a class function to retrieve the introduction? And with a function, we could also refresh the introduction if the player were traded to a new team or his position changed. Using the lazy initializer - it seems you’d be stuck with an out of date greeting? (I guess I’m having a hard time envisioning a use case in which using lazy would be better than making a class function.)
@seanallen
@seanallen 4 жыл бұрын
In your specific example, where we wanted the introduction to be flexible and take in parameters, then yes, a function could be better. At the end of the day, lazy, computed, or functions are very similar with slight variations that make each tool better for different situations. When it comes to the expensive computation example, the function, similar to the computed property, will end up calculating the value each time you call the function. Of course, in that function, you could set the property value so that it is stored on the object. But now that leads to confusion in using your code... you would use the function the first time (to calculate the value), then access the property each subsequent time so you didn't recalculate it.
@Tenly2009
@Tenly2009 4 жыл бұрын
Sean Allen Ok. Thanks. Off topic question if you don’t mind, but I know how to define class variables with a: var name:String = “Default Name” var name:String? ...but I recently saw one initialized as: var name:String! ...which I’ve never seen before and assumed would throw an error... is there some quick and simple explanation for this syntax? (A quick google search didn’t return anything useful)
@seanallen
@seanallen 4 жыл бұрын
That's what's known as an implicitly unwrapped optional. You should only initialize something like that if you know FOR SURE it will have a value before you access it. If not, it will crash. If you'd like to dive deeper, google "implicitly unwrapped optionals"
@lukasaudir8
@lukasaudir8 4 жыл бұрын
Good explanation, But why are you wrapping the lazy properties result in closures? As far as I know it's not mandatory, if you have only one simple value like a string you can just put lazy on the property and you're good to go
@seanallen
@seanallen 4 жыл бұрын
You are correct, they aren't mandatory unless there is logic in them.
@spaceowl5957
@spaceowl5957 2 жыл бұрын
Lazy also can’t change if it depends on other properties right?
@alexl2512
@alexl2512 9 ай бұрын
I got it. If a property is only computed once and is not needed when init and never changes, we should use lazy. If it changes we should use computed property. Am I right?
@seanallen
@seanallen 9 ай бұрын
Yup :)
@AmitBiswastunebox
@AmitBiswastunebox 4 жыл бұрын
Hey Sean what is Universal Self / Self keyword in Swift. Can you clear it please ?
@samha1513
@samha1513 2 жыл бұрын
Devmountian boot camp worth it?
@williamsquires3070
@williamsquires3070 Жыл бұрын
Okay, but the first example would be better handled with a simple computed property getter, I think, since no one is going to be able to ask for the .introduction until they create a Player variable anyway. It also avoids having to get rid of the unwanted argument to the default init method when you create a Plaver instance. I’m just not sure “lazy” adds any advantages here.
@kishanvaghela9942
@kishanvaghela9942 4 жыл бұрын
Hey do you know you can use lazy on arrays as well!! like array.lazy.filter { $0.some condition}
@seanallen
@seanallen 4 жыл бұрын
It can be used in many more ways than I showed. I didn't want to overwhelm the audience by showing a ton of examples. This is meant for people just learning about lazy. But thanks for sharing that example for others to see 👍
@kishanvaghela9942
@kishanvaghela9942 4 жыл бұрын
Esther van Enckevort i am stuck at returns view. Can explain little bit more?
@kishanvaghela9942
@kishanvaghela9942 4 жыл бұрын
Esther van Enckevort yes right! It returns lazy sequence or collection.
@pavanmanjani7583
@pavanmanjani7583 4 жыл бұрын
Sean, I have one question I think we can use lazy like this too:- var gamesPlayed = Calulator.calulateGamesPlayed() If yes your answer is then what is the difference????
@seanallen
@seanallen 4 жыл бұрын
You can do that. You don't really need the closure unless you are doing logic and have multiple lines of code.
@pavanmanjani7583
@pavanmanjani7583 4 жыл бұрын
@@seanallen got it👍
@3909630
@3909630 4 жыл бұрын
So is lazy a keyword for async?
@onlydubz558
@onlydubz558 4 жыл бұрын
very nicely explained... u should be a professor or something XD
@seanallen
@seanallen 4 жыл бұрын
Hehe, thanks for the kind words. I'm creating my own online courses in iOS development, so I guess that's kind of a professor 🤷🏻‍♂️
@aayushpareek8756
@aayushpareek8756 4 жыл бұрын
Can someone tell me what is this underscore mean in 4_000
@seanallen
@seanallen 4 жыл бұрын
It does nothing. It's just a way to split up the zeros like a comma. For example, if you had 4 million, it could be hard to figure out the number if you wrote it like 4000000. But when you write it like 4_000_000 it's easy to see that it's 4 million. Its purely stylistic. No functionality.
@aayushpareek8756
@aayushpareek8756 4 жыл бұрын
Sean Allen thanks for explaining
@seanallen
@seanallen 4 жыл бұрын
Happy to help!
@christinewang6484
@christinewang6484 3 жыл бұрын
is your favorite team bulls, and your favorite player Michael Jordan?
@OblivifrekTV
@OblivifrekTV 4 жыл бұрын
im too lazy
@RahulPahuja1991
@RahulPahuja1991 4 жыл бұрын
if i say struct Player{ var name:String var team:String var position:String lazy var introduction = { return "Now Entering the game \(name), \(position) for the team" }() } var jordan = Player(name: "Michael Jordan", team: "Shooters", position: "2") print(jordan) Question, Why Does it Print Player(name: "Michael Jordan", team: "Shooters", position: "2", $__lazy_storage_$_introduction: nil) on the other hand if i only say print(jordan.introduction) it prints Now Entering the game Michael Jordan, 2 for the team
@tilakmadichettitheappdeveloper
@tilakmadichettitheappdeveloper 4 жыл бұрын
how can i become your friend ?
Swift - Static Properties & Methods Explained
5:57
Sean Allen
Рет қаралды 28 М.
1❤️
00:17
Nonomen ノノメン
Рет қаралды 13 МЛН
That's how money comes into our family
00:14
Mamasoboliha
Рет қаралды 10 МЛН
1 or 2?🐄
00:12
Kan Andrey
Рет қаралды 52 МЛН
Swift Access Control Explained
9:44
Sean Allen
Рет қаралды 33 М.
Swift - Result Type - Cleaner Network Calls
12:07
Sean Allen
Рет қаралды 20 М.
Swift Closures Explained
14:23
Sean Allen
Рет қаралды 60 М.
How to create and use closures - Swift for Complete Beginners
18:39
Swift Structs - Value Type vs. Reference Type
7:54
Sean Allen
Рет қаралды 15 М.
Difference between weak and unowned in Swift
16:20
Code Cat
Рет қаралды 14 М.
LazyVGrid, LazyHGrid, and GridItems in SwiftUI | Bootcamp #16
22:16
Swiftful Thinking
Рет қаралды 42 М.
How I Would Learn to Code in 2024 (if I had to start over)
13:44
Internet Made Coder
Рет қаралды 66 М.
YOTAPHONE 2 - СПУСТЯ 10 ЛЕТ
15:13
ЗЕ МАККЕРС
Рет қаралды 187 М.
Собери ПК и Получи 10,000₽
1:00
build monsters
Рет қаралды 2,4 МЛН
НЕ ПОКУПАЙ СМАРТФОН, ПОКА НЕ УЗНАЕШЬ ЭТО! Не ошибись с выбором…
15:23
Clicks чехол-клавиатура для iPhone ⌨️
0:59