【发布时间】:2021-10-06 13:09:50
【问题描述】:
一直在搜索 SO 并通过谷歌搜索了一个小时。还没有找到确切的答案。因此,请验证我的理解。
结构与类
- 在 swift 中默认首选结构。
- 结构是
value type。班级是reference type
图片来自:https://cocoacasts.com/value-types-and-reference-types-in-swift
好的。这一切都很好,花花公子。现在类中的static func 和func 有什么区别?
static 只是意味着-> 静态,但是当它在一个类中并用于声明一个函数时?什么意思?
static 关键字与 final 类相同。 final 关键字使 变量或函数最终,即它们不能被任何覆盖 继承类。 (link)
class TestStruct {
var count = Int()
func popeye(name: String) -> String {
count = count + 1
return "TestStruct - func popeye - name:\(name) Count:\(count)"
}
static func brutus(name: String) -> String {
var count = Int() // when declared within the static func
count = count + 1 // this never gets incremented
return "TestStruct - static func brutus - name:\(name) count:\(count)"
}
}
我试过这个,发现我不能像 foo1.popeye 那样做 foo1.brutus,当它被分配了 static func 关键字时。
但作为 func,我可以有 2 个变量引用同一个函数,并且两者都有自己的值(下面的示例,count 输出不同)。那么使用static 有什么好处呢?我什么时候使用static func
let foo1 = TestStruct()
let foo2 = TestStruct()
var bar1 = foo1.popeye(name: "popeye sailorman")
var bar2 = foo2.popeye(name: "popeye spinach ")
print("foo1:\(bar1)")
print("foo2:\(bar2)")
bar1 = foo1.popeye(name: "popeye sailorman")
print("foo1:\(bar1)")
print("foo2:\(bar2)")
bar1 = foo1.popeye(name: "popeye sailorman")
print("foo1:\(bar1)")
print("foo2:\(bar2)")
bar1 = foo1.popeye(name: "popeye sailorman")
bar2 = foo2.popeye(name: "popeye spinach ")
print("foo1:\(bar1)")
print("foo2:\(bar2)")
var oliveOil1 = TestStruct.brutus(name: "Brutus Big ")
var oliveOil2 = TestStruct.brutus(name: "Brutus Mean")
print("oliveOil1:\(oliveOil1)")
print("oliveOil2:\(oliveOil2)")
oliveOil1 = TestStruct.brutus(name: "Brutus Big ")
oliveOil2 = TestStruct.brutus(name: "Brutus Mean")
print("oliveOil1:\(oliveOil1)")
print("oliveOil2:\(oliveOil2)")
导致这些打印输出:
foo1:TestStruct - func popeye - name:popeye sailorman Count:1
foo2:TestStruct - func popeye - name:popeye spinach Count:1
foo1:TestStruct - func popeye - name:popeye sailorman Count:2
foo2:TestStruct - func popeye - name:popeye spinach Count:1
foo1:TestStruct - func popeye - name:popeye sailorman Count:3
foo2:TestStruct - func popeye - name:popeye spinach Count:1
foo1:TestStruct - func popeye - name:popeye sailorman Count:4
foo2:TestStruct - func popeye - name:popeye spinach Count:2
oliveOil1:TestStruct - static func brutus - name:Brutus Big count:1
oliveOil2:TestStruct - static func brutus - name:Brutus Mean count:1
oliveOil1:TestStruct - static func brutus - name:Brutus Big count:1
oliveOil2:TestStruct - static func brutus - name:Brutus Mean count:1
【问题讨论】: