Swift - Static Properties & Methods Explained

  Рет қаралды 29,069

Sean Allen

Sean Allen

Күн бұрын

In this Swift tutorial I explain what the "static" keyword means and show off various examples and use cases. The main takeaway here is the difference between types and instances, and that the static variable, constant or method belongs tho the type.
This tutorial was built using Xcode 11 and Swift 5.1.
Swift Documentation on the topic:
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...
I stream gaming content 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...
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

Пікірлер: 109
@seanallen
@seanallen 4 жыл бұрын
Watch Next - iOS Take Home Project - Job Interview Practice - Free Preview - kzfaq.info/get/bejne/g7l5mJWqm6zJlWw.html
@adamm3122
@adamm3122 4 жыл бұрын
Duuuuude. Best practices examples would be killer!! Like organizing alerts, colors...
@seanallen
@seanallen 4 жыл бұрын
Many have requested this... may have to do that someday
@kdtechniquesofficial6153
@kdtechniquesofficial6153 Жыл бұрын
After years, I now understand what static really is and its use cases. Thanks, Sean.
@seanallen
@seanallen Жыл бұрын
Finally!
@nileshjdarji
@nileshjdarji 4 жыл бұрын
Great. So after using keyword static, creator becomes a Type property which every instance will have in common. Nicely explained. Thank you.
@seanallen
@seanallen 4 жыл бұрын
Glad it helped!
@KimbrellBrad
@KimbrellBrad 3 жыл бұрын
Thanks for sharing this link Sean. Now it makes sense. Now, more practice!
@sn3aky_pants593
@sn3aky_pants593 4 жыл бұрын
Thanks Sean. I never thought of using a static Alert enum before - gonna adopt that one for sure!
@seanallen
@seanallen 4 жыл бұрын
Glad you got something out of it, Brian!
@Eugene.Berezin
@Eugene.Berezin 4 жыл бұрын
Nice explanation! When I think about static I think about helper variables and helper methods. At least how I organized my code. I really liked how you explained it!
@seanallen
@seanallen 4 жыл бұрын
Glad you enjoyed it, Eugene!
@ahmadajr9507
@ahmadajr9507 4 жыл бұрын
Finally found a great explanation for static ! Thanks Sean!
@seanallen
@seanallen 4 жыл бұрын
Glad you found it helpful!
@danpgomez
@danpgomez 4 жыл бұрын
Love your content Sean! Super helpful and clear.
@seanallen
@seanallen 4 жыл бұрын
Glad to hear it's helpful, Daniel!
@user-zw7jl1bt3w
@user-zw7jl1bt3w 4 жыл бұрын
Sean, thanks for your work! You motivate a lot to learn and work harder
@Olden2610
@Olden2610 4 жыл бұрын
Nice attitude is always A Win :) Some day - it'll kick back in a nice way
@seanallen
@seanallen 4 жыл бұрын
Happy to help!
@efecetin5351
@efecetin5351 Жыл бұрын
You explained it amazingly. Thank you!
@gsd1075
@gsd1075 4 жыл бұрын
Great Video! In the topic, someday you could do one video about your code struct. Something like, why you do the instance of colors that way, or why you do table view with enum. This little secrets about the best ways to build our project. Thanks!
@seanallen
@seanallen 4 жыл бұрын
I've had a lot of requests for a best practices type video.
@berkeyagizsevim
@berkeyagizsevim 4 жыл бұрын
Nice explanation, again! Good job Sean. 👋🏻
@seanallen
@seanallen 4 жыл бұрын
Thanks Berke!
@MosabbirSadman
@MosabbirSadman Жыл бұрын
Honestly, I've encountered the static keyword before but didn't fully grasp its concept. Now that I've begun using it, I felt compelled to gain a comprehensive understanding. Your video explanation, complete with a perfect example from the documentation, was incredibly straightforward and saved me from aimless searching. Thanks! XD
@normandmartin7548
@normandmartin7548 4 жыл бұрын
Very clear and simple explanation, thanks!
@seanallen
@seanallen 4 жыл бұрын
Thanks Norman!
@gakkieNL
@gakkieNL 4 жыл бұрын
Good stuff. Short and simple 👍
@seanallen
@seanallen 4 жыл бұрын
Thanks Gakkie!
@HyperActive94
@HyperActive94 4 жыл бұрын
Thnx Sean! Great explanation
@seanallen
@seanallen 4 жыл бұрын
Happy to help, Ziko!
@profgallaugher
@profgallaugher 4 жыл бұрын
Thanks so much for your contributions! Your videos are really great & I always recommend them to others! Some of the comments below note the enum Alert v. the struct Alert & I remember you used struct Alert in your also quite awesome UIAlertController Refactor video, done about a year before this one. It'd be great to hear more on why/when to use structs v. enums (and perhaps even classes and Singletons) for reusable type functions that don't need an instance. I've created a simple set of functions for UserNotifications (e.g. authorize, setCalendarNotifications) & keep circling how to best to store them - static funcs in struct, enum, why not classes, etc. Also - have you ever done a video on best practices for magic strings? I'm using way too many string literals for everything from JSON keys to UI object identifiers. It'd be great to get some guidance on that. Once again, huge thanks & keep at it!
@seanallen
@seanallen 4 жыл бұрын
Hey John, the reason I switch to an enum was so that you can't initialize and empty object. It's a minor optimization. When it's a struct, you can initialize an empty one like Alert(), which can be confusing to the user of the code. As for too many string literals, I create a constants file that holds enums with static variables on it, so I can pass in something like "JSONKeys.something" to replace the string literal. I go over all the stuff you asked in my course at seanallen.teachable.com. But as far as videos on the KZfaq channel, none yet. Too many videos, too little time 😀
@erezmizrahi1631
@erezmizrahi1631 4 жыл бұрын
in my opinion you should do more videos like this one pick a "small topic" and simplify the topic like you did here I found this video very helpful!
@seanallen
@seanallen 4 жыл бұрын
I plan on doing more of these "keyword" videos. Glad you liked it
@airesnobeat
@airesnobeat 4 жыл бұрын
Great explanation... thanks
@seanallen
@seanallen 4 жыл бұрын
Thanks!
@w0mblemania
@w0mblemania 4 жыл бұрын
A very good explanation, thanks Sean. Another use for static is factory methods. i.e. being able to conveniently create an instance from the type itself, usually with some default values. e.g. let specialFoo = Foo.makeSpecialFoo()
@seanallen
@seanallen 4 жыл бұрын
Glad you liked it, and thanks for sharing another use case with factory methods.
@WhatIsThisAllAbout
@WhatIsThisAllAbout Жыл бұрын
A static property can't belong to a type because a type is not created in memory, objects are! "All objects of the type share the same static property". Its only because in code we say Type.staticProperty which gives the illusion that it belongs to type. A type doesn't exist in memory. So, a property can't belong to it. Correct me if I am wrong. Edit: your channel is the best channel IMO on the internet for iOS development.
@thevitruvianman9781
@thevitruvianman9781 4 жыл бұрын
Great Sean, I get this now..
@seanallen
@seanallen 4 жыл бұрын
Happy to help!
@DavidNoyMusic
@DavidNoyMusic 3 жыл бұрын
Thanks! Maybe it will be a good idea to add the "problems" with static too.
@vamsi3877
@vamsi3877 4 жыл бұрын
Helpful
@karljay7473
@karljay7473 4 жыл бұрын
It would be interesting to see more about how you used the alert in that sample code. I saw someone else's solution to having alerts inside of a class where it was very easy to show various alerts. Maybe you can go into a bit more detail on how you setup those alerts.
@seanallen
@seanallen 4 жыл бұрын
I did a video about that: kzfaq.info/get/bejne/kKiDZdiDtZzDYok.html
@abhishekbedi1432
@abhishekbedi1432 3 жыл бұрын
Amazing video Sean, Just one question. You said the Type owns variable. Well! Then how is the memory mapping impacted considering instance variable & typed variable?
@lennartphilipp6699
@lennartphilipp6699 4 жыл бұрын
Great tutorial! I noticed the awesome overview of your code on the right side of the screen :) How did you turn it on? Or did you use some sort of plugin for that?
@seanallen
@seanallen 4 жыл бұрын
That's a feature of Xcode 11 called mini-map
@seanallen
@seanallen 4 жыл бұрын
Watch Next - Delegates & Protocols - kzfaq.info/get/bejne/eqiHqJmF086wlY0.html
@Olden2610
@Olden2610 4 жыл бұрын
Small tip for 'Colors' thing. You actually can create extension on UIColor and set you custom colors there as Computed properties (not Stored), something like this: extension UIColor { var alunaBlue: UIColor { return UIColor(red: 108/255, green: 131/255, blue: 156/255, alpha: 1.0) } } Profit: Instead of 'Colors.alunaBlue' you write '.alunaBlue' (which is much convenient in practice then it seems like)
@Olden2610
@Olden2610 4 жыл бұрын
+ Would be great to explain (for those who don't know) difference between 'static' and 'class' Great video tho!
@seanallen
@seanallen 4 жыл бұрын
Good point about the UIColor extension.
@MrDangar11
@MrDangar11 4 жыл бұрын
I would add the main overused pattern with static “Singleton” and “Singleton +” the difference between them only private and public initialization that allow you to create additional instance not only let myClass = MyClass.shared but let myClass2 = MyClass()
@user-xy6qu5qi6c
@user-xy6qu5qi6c Жыл бұрын
Hey Sean I have a question about you, before working on iOS and Swift world, what did you do before? what language/framework di you used to use?
@seanallen
@seanallen Жыл бұрын
iOS and Swift is all I've ever known. It's what I learned to code with back in 2014. Been specializing in it ever sense.
@LUKAS-bb4jc
@LUKAS-bb4jc 4 жыл бұрын
Hi, your video was very helpful but how did set the spacing to be equal between all the = ? For instance var first = 1 and you have var second = 2 and have the equals to be vertically aligned ?
@seanallen
@seanallen 4 жыл бұрын
I manually tabbed them over. It's tedious and not all developers agree with that style. But I like it.
@FelipeCampelo0
@FelipeCampelo0 6 ай бұрын
The same in Flutter: most of static vars are class constants.
@nabilfarhat9190
@nabilfarhat9190 4 жыл бұрын
Can You please make an episode about local and push Notifications how to implement them and what they ask about in Interviews
@seanallen
@seanallen 4 жыл бұрын
My patreon community gets to vote and have a say it what topics I cover. If you're interested in that, check out patreon.com/seanallen
@newyorkdeveloper
@newyorkdeveloper 3 жыл бұрын
How do you align your variables to have the same exact location for = throughout each line?
@seanallen
@seanallen 3 жыл бұрын
I tab them over. It's a little tedious, for sure. But I like how it makes my code look find it more readable. To be clear, this is a subjective preference and not everyone likes it.
@theafzalansari01
@theafzalansari01 4 жыл бұрын
Thank you Sean this small stuffs really help us,Is it bad practice to use static method in singleton and call api in that method?
@w0mblemania
@w0mblemania 4 жыл бұрын
It's not inherently bad, no. If it reduces the complexity of your app, then it may be a very good idea. Singletons have their place. The problem is that they are often used when they shouldn't be. They are best used for Services, or to manage contending resource allocation where it's too tedious/messy to inject dependencies (e.g. along a chain of managers). Logging is often a decent use of a Singleton, because the alternatives can impose too many problems. But if the Singleton is really only being used as an escape hatch in a complex, unwieldy design, then it's not really the Singleton at fault; it's the app architecture (or lack thereof) which needs to be addressed. So the answer to your question is "it depends". Our goal should be to ship maintainable products, on schedule, within budget. Purity of design is a very secondary (and sometimes unwanted) concern.
@theafzalansari01
@theafzalansari01 4 жыл бұрын
w0mbles thnx for that explanation I’ll keep that in mind
@mmendes6780
@mmendes6780 4 жыл бұрын
What’s the difference of enum, class or struct?
@AnhLe-vb3ei
@AnhLe-vb3ei 4 жыл бұрын
Thanks Sean! I have a question, when you define constant, what is the different thing between using enum and struct, please!
@seanallen
@seanallen 4 жыл бұрын
It's a minimal difference... and enum can be better because if it's a struct you could initialize an empty one and have a random object out there. Doing something like Colors() will initialize an empty struct. You can't do that with an enum. So an enum is a little better for safety reasons in that example.
@JasonMitchellAZ
@JasonMitchellAZ 4 жыл бұрын
Was wondering why you switched to enums for Color, instead of still using structs... but that makes sense 👌
@Psztyk236
@Psztyk236 4 жыл бұрын
I always wondered, you can basically use a class with static methods, variabled kinda like you would use a singleton. Is this type of usage also discouraged? Singletons get a lot of bad publicity Anyway, I use static variables for settings in my app and it’s pretty convenient
@seanallen
@seanallen 4 жыл бұрын
You'll get a wide variety of opinions on Singletons. In my opinion it's very situational as to when to use them. It's a nuanced answer, not black and white.
@zoganauiti
@zoganauiti 4 жыл бұрын
at 4:55, how to your switch case on indexPath are being compared to these variables what are "patitients", "history"...?
@seanallen
@seanallen 4 жыл бұрын
They are just named variables for Int. This is for readability purposes. So instead of saying if indexPath == 2, I can said if indexPath == history. This is more clear to the reader of the code in my opinion.
@sudarshanderangula4819
@sudarshanderangula4819 4 жыл бұрын
Can you explain difference between class function and static function??
@seanallen
@seanallen 4 жыл бұрын
Check out this link here that explains it well: stackoverflow.com/questions/25156377/what-is-the-difference-between-static-func-and-class-func-in-swift
@smarter2610
@smarter2610 4 жыл бұрын
enum + static let or static func versus struct + static let or static func. Any difference in real life?
@seanallen
@seanallen 4 жыл бұрын
It's a minimal difference. But with a struct, you can initialize an empty one. Like Colors(). You can't do that with an enum. It's a minor safety thing. Not a huge deal in my opinion.
@user-yd9xy3rb4x
@user-yd9xy3rb4x 3 жыл бұрын
But enum Colors would work in the same way without static. Wouldn’t it?
@VincentGroenewold
@VincentGroenewold 4 жыл бұрын
Excellent video! But can you touch on the negatives of using static?
@robertwalker5660
@robertwalker5660 4 жыл бұрын
One VERY important consideration when using static is the fact that they live in global scope. It is almost always a bad idea to allow variables in the global scope. So static let myTypeConstant is fine, but static var myTypeVariable is generally a really bad idea. This can be the source of very hard to track down bugs in any application that uses more than one thread of execution. That is any modern application in case you didn’t catch on to that.
@VincentGroenewold
@VincentGroenewold 4 жыл бұрын
Robert Walker Thanks for the reply! I do see that indeed. And I guess it then also makes it harder to perform tests?
@w0mblemania
@w0mblemania 4 жыл бұрын
@@robertwalker5660 Yes, and no. It's true that they are (effectively) globals, but then we have to remember that EVERY non-nested type or function that we use in a project is actually a global. Yet we still manage to make complex programs with them. In fact, we NEED their global nature in order to access them. Thus the problem is not that something is global: the problem is about access, unintended consequences (mutation) and complexity. Using static properties and methods can be a way to reduce complexity and properly encapsulate certain types of functionality. And some times, it's simply the best, safest way to do it from amongst the various options we have. So, they're a tool in a toolbox, as are Singletons. Cheers.
@robertwalker5660
@robertwalker5660 4 жыл бұрын
w0mbles It’s not the fact that static variable are in the global scope, it’s that they are holding state in the global scope. Types and functions don’t really represent state in the same way as global variables do. Static types variables (A.K.A class variables) are generally a bad idea, in the same way as singletons are generally a bad idea. In both cases there are exceptions, but if you can avoid them, you’re better off avoiding them. There are lots of tools in a programmer’s tool chest. And, like most tool chests some of the tools are sort of broken.
@w0mblemania
@w0mblemania 4 жыл бұрын
@@robertwalker5660 Vincent asked about the merits of using static. There are pros and cons. And often, the greater evil is adding complexity through abstractions or delegation chains or boilerplate. And holding state is not a con in itself; state has to be held somewhere, after all. And sometimes the centralisation of that state through a static member on a Type is the best bet. And it's certainly a very good way to provide Factory mechanics.
@michaelthomas2090
@michaelthomas2090 2 жыл бұрын
what program are in coding in?
@seanallen
@seanallen 2 жыл бұрын
Xcode
@user-yd9xy3rb4x
@user-yd9xy3rb4x 3 жыл бұрын
You’ve never shared your GitHub or I missed something?
@getbiks
@getbiks 4 жыл бұрын
is it safe to use so many static variables?
@TreyCox1
@TreyCox1 4 жыл бұрын
I hope so because I use them everywhere lol...
@sn3aky_pants593
@sn3aky_pants593 4 жыл бұрын
In these examples, yes. Most of the concern is around singletons (ie: static let shared = ModelController()), which are really useful but can also be abused.
@_DeProgrammer
@_DeProgrammer 4 жыл бұрын
you have 10-20 show(something) functions to show an alert that take a vc and a message. As a programmer when you repeat yourself like that it should ring alarm bells.
@w0mblemania
@w0mblemania 4 жыл бұрын
Principles like DRY are tools, rather than rules. Sometimes, factoring code out is not worth the effort in terms of clarity. And premature refactoring is a root of many kinds of evil. It's the sort of clean up you can do towards the end of a project.
@kisivan92
@kisivan92 4 жыл бұрын
Another typical use case of static functions is in factory classes, I was hoping you'll tell briefly about that too, however constants might be even more common :) For those to whom the factory pattern might be unknown, check this article out: swiftcraft.io/swift-solutions-factory-method-pattern/ Great video Sean, as always. Keep on going!
@seanallen
@seanallen 4 жыл бұрын
Thanks for sharing that, Peter
@MarcosVicente0
@MarcosVicente0 4 жыл бұрын
I kinda didn't understand the difference between just using a constant and using a static constant.
@batrarohit1
@batrarohit1 4 жыл бұрын
Does he look at his keyboard to type???
@seanallen
@seanallen 4 жыл бұрын
I had a microphone on the desk between me and the keyboard. It’s tricky to type around it.
@stevenshrii
@stevenshrii 2 жыл бұрын
Pointer
@donathmm3881
@donathmm3881 4 жыл бұрын
Why is your alert an enum and not a class
@seanallen
@seanallen 4 жыл бұрын
My alert doesn't need to to be subclassed and there's no need for inheritance here.
@donathmm3881
@donathmm3881 4 жыл бұрын
Sean Allen but you only need to use enum if you have cases or not?
@seanallen
@seanallen 4 жыл бұрын
Nope. An enum can be much more flexible than that 😀
@donathmm3881
@donathmm3881 4 жыл бұрын
Sean Allen that's nice. But is it the same to use a singelton class instead? And what if you make for example network calls where you also don't need inheritance etc.
@americanyoyo2
@americanyoyo2 4 жыл бұрын
First Comment 😝
@seanallen
@seanallen 4 жыл бұрын
Love the quickness...
@alexandr8328
@alexandr8328 4 жыл бұрын
Sean Allen Even when with lady? 😏
Swift Access Control Explained
9:44
Sean Allen
Рет қаралды 33 М.
Swift Closures Explained
14:23
Sean Allen
Рет қаралды 62 М.
Каха заблудился в горах
00:57
К-Media
Рет қаралды 10 МЛН
لااا! هذه البرتقالة مزعجة جدًا #قصير
00:15
One More Arabic
Рет қаралды 20 МЛН
Doing This Instead Of Studying.. 😳
00:12
Jojo Sim
Рет қаралды 23 МЛН
How to use Lazy in Swift
9:56
Sean Allen
Рет қаралды 39 М.
Static properties and methods - Swift for Complete Beginners
9:05
Swift Structs - Value Type vs. Reference Type
7:54
Sean Allen
Рет қаралды 15 М.
Static Keyword in 7 Minutes (Swift, Xcode)
7:19
CodeBrah
Рет қаралды 398
Swift For Beginners - Class & Inheritance Explained
15:42
Sean Allen
Рет қаралды 16 М.
Turns out REST APIs weren't the answer (and that's OK!)
10:38
Dylan Beattie
Рет қаралды 129 М.
JPEG is Dying - And that's a bad thing
8:09
2kliksphilip
Рет қаралды 116 М.
How to use a Switch Statement in Swift | Beginner
11:27
Sean Allen
Рет қаралды 8 М.
Computed Properties in Swift
6:39
Stewart Lynch
Рет қаралды 6 М.
iPhone socket cleaning #Fixit
0:30
Tamar DB (mt)
Рет қаралды 18 МЛН
Как удвоить напряжение? #электроника #умножитель
1:00
Hi Dev! – Электроника
Рет қаралды 1,1 МЛН
Это iPhone 16
0:52
Wylsacom
Рет қаралды 1 МЛН