gpt4 book ai didi

swift - 包装到没有特定泛型类型的函数中时不调用正确的方法

转载 作者:搜寻专家 更新时间:2023-11-01 05:34:29 25 4
gpt4 key购买 nike

我正在 Playground 上试验的示例代码

protocol Shape {
init()
}

class Circle: Shape {
required init() {
}
}

class Square: Shape {
required init() {
}
}

class ShapeMapping<T> {
func map() -> T? {
print("Any shape called")
return nil
}
}

extension ShapeMapping where T: Shape {
func map() -> T? {
print("Shape type called")
return T.self()
}
}

extension ShapeMapping where T: Square {
func map() -> T? {
print("Square type called")
return Square() as? T
}
}

class ShapeWrapper<T> {
func determineShape() -> T? {
return ShapeMapping<T>().map()
}

}

当我调用

时,代码工作正常并调用 Square 类型的预期方法
let square: Square? = ShapeMapping<Square>().map()

Output: Square type called

但是,当我调用包装器方法并传递 Square 类型时,输出是不同的

let mappingSquareShape: Square? = ShapeWrapper<Square>().determineShape()

Actual: Any shape called
Expected: Square type called

类型信息没有从 ShapeWrapper 传递到 ShapeMapping 吗?知道这里发生了什么吗?

最佳答案

在你的代码中,我发现当我定义类 ShapeMapping() 时,“func map()”会产生歧义,编译器将不知道使用哪一个,也许你可以在扩展中更改方法名称

extension ShapeMapping where T: Shape{
func test() -> T? {
print("Shape type called")
return nil
}
}

关于swift - 包装到没有特定泛型类型的函数中时不调用正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44212080/

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