Static - when do we use it?

Static - when do we use it?

First, if you don’t know the difference between Type & Instance:

Type is the definition of a class \ struct .

Instance - is the creation \ a single show of that type.

for example (from Sean's Allen Channel):

No alt text provided for this image

The functions\variables belongs to the instance, meaning that we cannot access those functions\variables unless we create an instance.

if we want a function \ variable for the Type - we’ll use the static keyword.

in docs.swift.org we have an example of it’s use:

No alt text provided for this image

All of the game’s levels (apart from level one) are locked when the game is first played. Every time a player finishes a level, that level is unlocked for all players on the device. The LevelTracker structure uses type properties and methods to keep track of which levels of the game have been unlocked.


More examples from Sean’s Allen channel - using static to define constants like Colors, Fonts and Alerts for cleaner code:

enum Colors{ 
??? static let alunaBlue = UIColor(red: 108/255, green: 131/155, blue: 156/255, alpha: 1)
??? //add more colors…

}

enum Fonts {
??? static let spaceComics = "Space Comics"
??? //add more fonts…
}

enum Alert{
??? static func show(title: String, message: String, vc: UIViewController, andEnable button: UIButton? ){
??????? let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
??????? let action = UIAlertAction(title: "OK", style: .default) { _ in
??????????? if let button = button {
??????????????? button.isEnabled = true
??????????? }
??????? }
??????? alert.addAction(action)
??????? DispatchQueue.main.async {
??????????? vc.present(alert, animated: true)
??????? }
??? }
??? //add more custom alerts…
}        

And how to use it:


class viewController : UIViewController {
??? let newColor = Colors.alunaBlue
??? let fontName = Fonts.spaceComics

??? override func viewDidLoad() {
??????? super.viewDidLoad()
??????? Alert.show(title: "Welcome!", message: "this is your dashboard!", vc: self, andEnable: nil)
??? }
}        


Another way for static use - as a Singleton pattern, as shown in this example here:


class NetworkManager {
  static let shared = NetworkManager()
   
  func fetchData() {
      //fetchData makes an API call to download data.
    }

  func sendData(){
     //sendData makes an API Call to upload data. 
      } 
  }        

and it's use:


class viewController : UIViewController{

??? override func viewDidLoad() {
??????? super.viewDidLoad()
??????? NetworkManager.shared.fetchData()
??? }
}        

In conclusion:

use static to create a function \ method \ variable \ constant?which belongs to the Type and not the Type?Instance.

we will use it if we don’t need to instantiate an instance, or if we need a global func \ variable for the type (counter for example)

Dor Strauss

Backend Software Engineer - Developed and maintained the Backend infrastructures of commercial companies | Python | Django | FastAPI | AWS | AI (New post every Tuesday!)

2 年

Interesting, thank you for sharing.

回复
Eli Abraham

Back End Developer - Developing Infrastructures That Streamline Complex Processes And Create Personalized User Experiences | JavaScript | NodeJS | MongoDB | AWS | Docker | K8

2 年

Great content!! Thanks for sharing ????

回复
Dan Cohen

Unity Developer at @Qnigame - Creating VR Games, Casual Games and Strategic Games | Unity 3D | C# | Unreal Engine 4 | 5 | Blueprint | OOP | Design Patterns

2 年

Thanks

回复
Yoav Karsenty

Data Analyst –Extracting business insights from large datasets enabling various profit-maximizing actions. Assists athletes in determining their data-driven market value and how to increase it | Python | SQL | Excel

2 年

thanks man very interesting !

回复

要查看或添加评论,请登录

Aviram Netanel的更多文章

  • UIKit vs. SwiftUI - TableView \ List

    UIKit vs. SwiftUI - TableView \ List

    I wrote 2 projects that shows a tableview \ list with expandable cells. The idea is simple: you have a table \ list…

    4 条评论
  • Swift - didSet{...} Property Observer

    Swift - didSet{...} Property Observer

    if you're not familiar with the 'didSet' property observer - this is for you: with this simple trick you can execute a…

    1 条评论
  • Swift - Building a custom framework

    Swift - Building a custom framework

    A quick tutorial for building and importing a custom SDK to your project. save it for a rainy day.

    1 条评论
  • Swift - the 'required' keyword

    Swift - the 'required' keyword

    Did you ever get this error? 'required' initializer 'init(coder:)' must be provided by subclass of..

    1 条评论
  • Swift - Array map, flatMap & compatMap

    Swift - Array map, flatMap & compatMap

    map, flatMap & compactMap are Array methods for manipulation. here are few simple examples to help you understand, and…

  • SwiftUI Pagination

    SwiftUI Pagination

    Pagination in SwiftUI & MVVM. In this example I'll show how to handle pagination: 1) Let's start with our ContentView:…

    2 条评论
  • The keyword 'some' - Swift \ SwiftUI

    The keyword 'some' - Swift \ SwiftUI

    If you ever started a SwiftUI project, you've probably noticed this 'some' keyword. so what's that? The keyword 'some'…

    7 条评论
  • UIViewController - Lifecycle

    UIViewController - Lifecycle

    This is one of the most common questions in interviews, so you better know this one. In General Every view controller…

    9 条评论
  • @escaping closures in Swift

    @escaping closures in Swift

    In short: We will use @escaping when the closure needs to outlive the life of its function More: when we pass a closure…

    5 条评论
  • Arguments and Parameters

    Arguments and Parameters

    Arguments and Parameters What's the difference? Parameter is the variable in the declaration of the function. Argument…

    4 条评论

社区洞察

其他会员也浏览了