What is the reason you can't use static methods/variables in a class [closed] - swift

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I was wondering why you cant use the static keyword in a class.
I know that you can use it in a struct but not in a class
Does anyone know why they choose for this?
And if so are there any advantages for letting static away?

It is a terminological bêtise. What Apple did was decide that you use static in an enum or struct and class in a class. In my view this was a very foolish decision, as they are exactly parallel to one another. Many people have posted on the dev forums suggesting that they just call them all static.
The outcome is a candidate for Occam's Razor: two phrases, e.g. static property and class property, or static method and class method, that mean exactly the same thing. And then they try to cover their tracks in the documentation by adding a third term as an umbrella, "type property" (meaning a static-or-class property) or "type method" (meaning a static-or-class method), which just makes the situation even worse.
The badness of the situation is also revealed by what you have to do in protocols: you declare a class property in a protocol and then if a struct adopts it, it calls that a static property. Same thing with a class method in a protocol; an adopting struct must call that a static method. You'd think that this alone would have told them they'd done a bad thing.
Edit: The more I think about it, the more I like the proposal put forth by newacct in a comment below. If Apple had simply used the umbrella keyword type here as part of the language, the whole problem would have been solved. We could have declarations type var, type let, type func, and this would work equally in enums, structs, classes, and protocols across the board.

From the Swift Language Guide on Methods, Apple has chosen to differentiate the syntax used, based upon the fundamental Type that you're building.
Classes declare "Type Methods" with the keyword Class. Example:
class MyClass {
class func myFunc(){ ... }
}
Structs declare "Type Methods" with the keyword Static. Example:
struct MyStruct {
static func myFunc(){ ... }
}
In both cases, crating a Type Method allows you to invoke the method without first creating an instance of the class or struct.
Whereas a non class/static function would require something like
let instance = MyClass()
instance.myFunc()
... declaring the variable as a Type Method allows something like
MyClass.myFunc()

Related

Naming of filenames, classes and protocols? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
When I use protocols with structural patterns such as MVP, or VIPER I usually add protocol and class conforming to the protocol in the same file.
For example, in MVP for the View component:
file: ListViewController.swift
protocol ListView {}
class ListViewController: ListView {}
and for the Presenter component:
file: ListPresenter.swift
protocol ListPresenter {}
class MainListPresenter : ListPresenter {}
1) is adding protocols and classes (when there is only one class conforming to it) in the same file, a good practice?
2) is ok to name the file containing the view controller with its name?
3) can I name the presenter file with the protocol name or do I lack of consistency?
How would you name filenames and classes in this example?
thanks
1) is adding protocols and classes (when there is only one class conforming to it) in the same file, a good practice?
If there's only one class conforming to a protocol, I would strongly argue that you're misusing protocols. If your pattern encourages this, then I would strongly question the value of the pattern.
But putting them in the same file is fine. Placing closely related types in a single file is good.
2) is ok to name the file containing the view controller with its name?
Sure.
3) can I name the presenter file with the protocol name or do I lack of consistency?
Sure...but again, if you have a protocol that has exactly one implementation, then something is likely wrong, and you should be digging into improving that rather than filenames.

Is convenience keyword really necessary in swift? [duplicate]

This question already has answers here:
Why convenience keyword is even needed in Swift?
(6 answers)
Closed 5 years ago.
The convenience keyword in swift completely confused me. It doesn't seem useful at all. Calling other initializer (or say constructor) in same or super class is a very common feature in object oriented languages, like Java, C# and etc. If any member is not initialized, the compiler gives a warning. It seems the only thing it does is to restrict the call to other initializer to same class, which makes it seems even more useless. So, why bother having this keyword at all?
I saw some other threads online discussing about this but none of them is really convincing.
Does anyone know the real purpose of this keyword?
From The Swift Programming Language:
You do not have to provide convenience initializers if your class does not require them. Create convenience initializers whenever a shortcut to a common initialization pattern will save time or make initialization of the class clearer in intent.
So, basically, they are for convenience.

A guess that the Swift type alias mechanism is the automatic initializer Inheritance

The question popped in my head, what is happening when I define a Swift type alias? What is the mechanism behind it? Until I learned the Automatic Initializer Inheritance chapter from the Swift official document:
If your subclass doesn't define any designated initializer, it automatically inherits all of its superclass designated initializers
And here is my practice code for learning
class Vehicle{
var numberOfWheels = 0
var description: String {
return "\(numberOfWheels) wheel(s)"
}
}
class Auto: Vehicle{}
let VM = Auto()
VM.numberOfWheels
Wow! this works,at least performs, exactly as the Swift type alias. Auto is the alias of the type Vehicle
Question: Am I understand it right? This is the mechanism behind type alias.
Question: Am I understand it right? This is the mechanism behind type alias.
NO, typealises and subclassing (with inheriting all methods and initializers) are different things and based on different semantics and mechanisms.
let v1 = Vehicle()
v1 is Auto //->false
typealias Norimono = Vehicle
v1 is Norimono //->true (with warning "'is' test is always true)
The last result (including the warning you may find) is exactly the same as v1 is Vehicle.
Typealias is literally an alias, it's giving another name for the same type.
One more, you can define typealias of structs or enums, which you cannot define inherited classes (types).
Not really, but if you've never seen object oriented programming they could look somewhat similar, i agree.
Auto is a subclass that extends the original vehicle and could add additional properties and method to the Vehicle even if in that example it doesn't do it.
Auto and Vehicle are not the same thing, a Vehicle is a basic type and and Auto is one of its subtypes, what you can do with a Vehicle you can do with an Auto but not vice-versa.
A typealias is just an alias, a way to give and additional "name" to a pre-existing type, just that. A type and his alias are the same thing.

Use of a Structure instead of a Class in Swift [duplicate]

This question already has answers here:
Why Choose Struct Over Class?
(17 answers)
Closed 7 years ago.
I learn Swift from some time, I know the differences between structure and class. The main difference is structure is of value type and class is of reference type but didn't understand when to use structure instead of a class. Please explain it.
For example, In case of Protocols:
First, We have just a protocol of struct type:
protocol SomeProtocol{
func doSomeStuff()
}
Second, We make protocol of class type like this:
protocol SomeProtocol: class{
func doSomeStuff()
}
So, Please explain me, when we have to use protocol of struct type or of class type.
Firstly structs are passed by value (copied), and a class is passed by reference (copied just the memory address to the object).You may want to use structs for simpler types, because you get a free init for all the properties your struct has.And with protocols, the first one you can use it on class,struct and enum, the second you say that you only use that on classes,and you may want to put class if your protocol is a delegate or a data source,because you want the property(of the type of your protocol) weak to avoid the memory cycle. IMHO use classes for multi-scene apps because you don't need to take care to update value when you edited something in an another scene.
The protocol is not "of struct type" or "of class type", that is wrong terminology.
If you write SomeProtocol: class you make sure only classes can conform to that protocol, structs cannot. If you don't include the class both classes and structs can conform.
The docs (scroll down to "Class-Only Protocols") tell you that
You can limit protocol adoption to class types (and not structures or enumerations) by adding the class keyword to a protocol’s inheritance list. The class keyword must always appear first in a protocol’s inheritance list, before any inherited protocols.
Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics. For more on reference and value semantics, see Structures and Enumerations Are Value Types and Classes Are Reference Types.

Template parameter: enum, class or enum class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Consider the following class:
template <class Endianness>
class bitcode
{};
With Endianness that could be: default_endianness, little_endian or big_endian.
The question is the following: according to C++14 and the following C++17, what is/will the best and common practices? (by common I mean those used (or which will be used) by the standard library or boost. (+ and why?)
// The enum option
enum enum_endianness {default_endianness, little_endian, big_endian};
// The enum class option
enum class enum_class_endianness {default_endianness, little_endian, big_endian};
// The class option
class class_default_endianness{};
class class_little_endian{};
class class_big_endian{};
(Note: of course the declaration of bitcode will depend on the prefered option.)
You have to choose what fits your end:
enum: It is mostly for backwards compatability.
enum class: Can only be used when you know all the tags in advance.
class: Anyone can introduce new tags and you can make the tags contain data.
enum class is most appropriate. It is a type-safe, scoped enumeration. You can compare values using the == operator, and also apply template specialization and deduction using template parameters.
enum alone is an unscoped enumeration. These are mostly considered a backward compatibility feature with C++98 and C. Values will implicitly convert to int, but those integers will be meaningless.
class alone gets you dispatch tags. Although this will work, you won't have the == and != operators, which might force you into excessive use of templates and overloads.
Another pattern to consider is the type-traits pattern: a class containing static data members and functions, so you don't have to add more template parameters.
enum class endianness {little_endian, big_endian};
class little_endian_traits {
static const enum endianness endianness = endianness::little_endian;
};
class big_endian_traits {
static const enum endianness endianness = endianness::big_endian;
};
typedef little_endian_traits default_endian_traits; // depending on platform
template< class traits >
class bitcode;
The choice is somewhat subject, but if you want to use this as a template parameter (e.g. for your bitcode class template), I'd stick with class/struct tags. This tends to make template programming simpler than mixing things templated on types with things templated on particular constant values.