I am not able to find any difference between class static function
to struct static function
. As I know class static function can not be inherited and struct does not have an option for inheritance.
Please do not get confused by static func and class func in class.
class a {
static func myMethod1() {
}
}
vs
struct a {
static func myMethod1() {
}
}
Class functions are dynamically dispatched and can be overridden by subclasses. Static functions are invoked by a class, rather than an instance of a class. These cannot be overridden by a subclass.
Where static and class differ is how they support inheritance: When you make a static property it becomes owned by the class and cannot be changed by subclasses, whereas when you use class it may be overridden if needed.
With the introduction of Swift, there are multiple ways to write such functions. Static Functions. Static functions are invoked by the class itself, not by an instance. This makes it simple to invoke utility functions without having to manage an object to do that work for you.
A struct can have its own static and instance methods (or functions) but are not created within the struct itself. These methods exist in a separate block using impl and they can be either static or instance methods.
This is kind of a stretch, but due to the reference vs value semantics of class
and struct
types, respectively, there is subtle difference in in the realization of a case where you want to make use of a type method (static
) to mutate a private property of the type, given an instance of the type has been supplied. Again, kind of a stretch, as this focuses on differences in implementation details, and not on a concrete difference between the two.
In the class
case, an immutable reference can be supplied to the static
method, which in turn can be used to mutate a private instance member of the type. In the case of the struct
, the instance of the type naturally needs to be supplied as an inout
parameter, as changing the value of an instance member of a value type also means changing the value of the instance itself.
class A {
private(set) var i: Int = 0
static func foo(_ bar: A) {
bar.i = 42
}
}
struct B {
private(set) var i: Int = 0
static func foo(_ bar: inout B) {
bar.i = 42
}
}
let a = A()
var b = B()
A.foo(a)
print(a.i) // 42
B.foo(&b)
print(b.i) // 42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With