gpt4 book ai didi

swift - 未调用快速扩展中的通用覆盖

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:11 25 4
gpt4 key购买 nike

我有一个泛型

enum ResultState<T> {
case found(T)
}

有一些扩展

extension ResultState {

func hello() { print("Hello") }
}

extension ResultState where T: Collection {

func hello() { print("Hello, collection") }
}

这些工作完美且完全符合我的预期:

ResultState.found(1).hello() // prints "Hello"
ResultState.found([1]).hello() // prints "Hello, collection"

但是,如果它们是从另一个通用函数中调用的,它的行为就不一样了

func myFunction<T>(_ state: ResultState<T>) {
state.hello()
}

例如,

myFunction(ResultState.found(1)) // prints "Hello"
myFunction(ResultState.found([1]) // prints "Hello"

现在,基本版本的 hello 每次都会被调用,即使检查 T 也是如此里面myFunction显示它肯定是 Array<Int> .

这是预期的 Swift 行为吗?

如果是这样,我该如何解决 - 我怎样才能获得正确版本的 hello从内部调用 myFunction

最佳答案

在我看来,myFunction 的信息丢失了,并且只应用了一个级别,可以说是 ResultState。不确定这是您想要的解决方案,但一种方法是以具有不同扩展的相同方式定义不同的函数。

func myFunction<T: Collection>(_ state: ResultState<T>)  {
state.hello()
}

func myFunction<T>(_ state: ResultState<T>) {
state.hello()
}

执行

ResultState.found(1).hello() 
ResultState.found([1]).hello()

myFunction(ResultState.found(1))
myFunction(ResultState.found([1]))

会产生

Hello
Hello, collection
Hello
Hello, collection

关于swift - 未调用快速扩展中的通用覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56127704/

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