Differences between "static var" and "var" in Swift

What is the main difference between “static var” and “var” in Swift? Can someone explain this difference to me, perhaps with a small example?

+6
source share
3 answers

static var belongs to the type itself, and var belongs to the instance (a specific type of a particular type). For instance:

 struct Car { static var numberOfWheels = 4 var plateNumber: String } Car.numberOfWheels = 3 let myCar = Car(plateNumber: "123456") 

All cars have the same number of wheels. You change it to type Car .

To change the plate number, you need to have a Car instance. For example, myCar .

+10
source

Static var is a property variable in the structure and an instance of the structure. Note that static var may exist for enumeration as well.

Example:

 struct MyStruct { static var foo:Int = 0 var bar:Int } println("MyStruct.foo = \(MyStruct.foo)") // Prints out 0 MyStruct.foo = 10 println("MyStruct.foo = \(MyStruct.foo)") // Prints out 10 var myStructInstance = MyStruct(bar:12) // bar is not // println("MyStruct.bar = \(MyStruct.bar)") println("myStructInstance = \(myStructInstance.bar)") // Prints out 12 

Pay attention to the difference? bar is defined on an instance of the structure. While foo is defined in the structure itself.

+1
source

I will give you a very good Swifty example based on this post . Although it is a little more complicated.

Imagine that you have a project in which you have 15 collectionViews in your application. For each of them, you must set cellIdentifier and nibName. Are you sure you want to rewrite all the code for your 15 times?

There is a very POP solution in your problem:

Help yourself by writing a protocol that returns a string version of our ClassName

 protocol ReusableView: class { static var defaultReuseIdentifier: String { get } } extension ReusableView where Self: UIView { static var defaultReuseIdentifier: String { return String(Self) } } extension BookCell : ReusableView{ } 

The same goes for the nibName each custom cell you created:

 protocol NibLoadableView: class { static var nibName: String { get } } extension NibLoadableView where Self: UIView { static var nibName: String { return String(Self) } } extension BookCell: NibLoadableView { } 

So now that I need nibName , I would just do

 BookCell.nibName 

And where I need a cellIdentifier , I would just do:

 BookCell.defaultReuseIdentifier 

Now specifically to your question. Do you think we need to change cellIdentifier to each new instance of BookCell ?! No! All BookCell cells will have the same identifier. This is not something that would change by one instance. The result was static

While I was answering your question, the decision to reduce the number of rows for 15 collectionViews can still be significantly improved, so see the blog post.


This blog post has actually been turned into a video by NatashaTheRobot

+1
source

Source: https://habr.com/ru/post/978930/


All Articles