gpt4 book ai didi

Swift 调用静态方法 : type(of: self) vs explicit class name

转载 作者:IT王子 更新时间:2023-10-29 05:08:28 25 4
gpt4 key购买 nike

在 swift 中,实例 func 不能调用 static/class func 而不在方法调用前加上类名作为前缀。或者您可以使用 type(of: self),例如

class Foo {
static func doIt() { }

func callIt() {
Foo.doIt() // This works
type(of: self).doIt() // Or this

doIt() // This doesn't compile (unresolved identifier)
}
}

我的问题是,这里有什么区别?这只是编码风格的问题,还是有一些差异,例如正在进行静态或动态调度?

如果只是编码风格,首选的风格是什么?

最佳答案

有两个主要区别。

1。静态方法中self的值

调用静态方法的元类型在方法中作为 self 可供您使用(它只是作为隐式参数传递)。因此,如果您在 type(of: self) 上调用 doIt() , self 将是实例的 dynamic 元类型。如果你在 Foo 上调用它,self 将是 Foo.self

class Foo {
static func doIt() {
print("hey I'm of type \(self)")
}

func callDoItOnDynamicType() {
type(of: self).doIt() // call on the dynamic metatype of the instance.
}

func classDoItOnFoo() {
Foo.doIt() // call on the metatype Foo.self.
}
}

class Bar : Foo {}

let f: Foo = Bar()

f.callDoItOnDynamicType() // hey I'm of type Bar
f.classDoItOnFoo() // hey I'm of type Foo

这种差异对于工厂方法确实很重要,因为它决定了您创建的实例的类型。

class Foo {
required init() {}

static func create() -> Self {
return self.init()
}

func createDynamic() -> Foo {
return type(of: self).create()
}

func createFoo() -> Foo {
return Foo.create()
}
}

class Bar : Foo {}

let f: Foo = Bar()

print(f.createDynamic()) // Bar
print(f.createFoo()) // Foo

2。静态方法的调度

( Martin has already covered 这个,但我想我会为了完成而添加它。)

对于在子类中被重写的 class 方法,调用该方法的元类型的值决定调用哪个实现。

如果调用编译时已知的元类型(例如 Foo.doIt()),Swift 能够静态分派(dispatch)调用。但是,如果您在直到运行时才知道的元类型上调用该方法(例如 type(of: self)),该方法调用将动态分派(dispatch)到元类型值的正确实现。

class Foo {
class func doIt() {
print("Foo's doIt")
}

func callDoItOnDynamicType() {
type(of: self).doIt() // the call to doIt() will be dynamically dispatched.
}

func classDoItOnFoo() {
Foo.doIt() // will be statically dispatched.
}
}


class Bar : Foo {
override class func doIt() {
print("Bar's doIt")
}
}

let f: Foo = Bar()

f.callDoItOnDynamicType() // Bar's doIt
f.classDoItOnFoo() // Foo's doIt

关于Swift 调用静态方法 : type(of: self) vs explicit class name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42260337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com