Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between struct static func vs class static func in swift?

Tags:

struct

swift

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() {
    }
}
like image 536
Retro Avatar asked Mar 31 '17 08:03

Retro


People also ask

What is difference between class Func and static func Swift?

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.

What is difference between class and static variable in Swift?

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.

What is static func in Swift?

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.

Can struct have static functions?

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.


1 Answers

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
like image 156
dfrib Avatar answered Oct 10 '22 23:10

dfrib