gpt4 book ai didi

Swift 协议(protocol)和扩展,如果存在,我需要调用实例方法

转载 作者:行者123 更新时间:2023-11-28 13:46:47 24 4
gpt4 key购买 nike

我有一个协议(protocol) Foo 及其扩展如下:

protocol Foo {
func test()
}

extension Foo {
func test() {
print("foo")
}
}

我也有这样的协议(protocol)类:

class Bar: Foo {
func test() {
print("bar")
}
}

测试器如下:

func tester<T: Foo>(_ obj: T) {
obj.test()
}

let myBar = Bar()
tester(myBar)

在输出中我有:

foo

但在意料之中 - 酒吧

我如何从我的tester调用实例方法test()

最佳答案

这一切都取决于两件事:

  • 这是协议(protocol)的要求还是仅由扩展注入(inject)?
  • 接收器类型是 Foo 还是 Bar?

例如:

protocol Foo {
// func test() // note we've commented this out!
}
extension Foo {
func test() {
print("foo")
}
}
class Bar: Foo {
func test() {
print("bar")
}
}
let myBar = Bar()
myBar.test() // bar
let myFoo : Foo = Bar()
myFoo.test() // foo

但是如果您取消注释我注释掉的行,现在您总是打印“bar”

关于Swift 协议(protocol)和扩展,如果存在,我需要调用实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310598/

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