Difference between struct static func vs class static func in swift?
我找不到
Please do not get confused by static func and class func in class.
1 2 3 4 | class a { static func myMethod1() { } } |
VS
1 2 3 4 | struct a { static func myMethod1() { } } |
这是一种延伸,但是由于
在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
不同的是,子类可以重写类方法,但不能重写静态方法。
下面是在操场上测试的简单示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class A{ class func classFunction(){ } static func staticFunction(){ } } class B: A { // override successfully override class func classFunction(){ } //Compile Error. Cannot override static method override static func staticFunction(){ } } |
这些链接可以帮助您理解这些功能。正如@mipadi所说(强调我的):
static andclass both associate a method with a class, rather than an
instance of a class. The difference is that subclasses can override
class methods; they cannot overridestatic methods.
class properties will theoretically function in the same way
(subclasses can override them), but they're not possible in Swift yet.
在swift中静态func和类func有什么区别?
Swift类中的静态与类函数/变量?