我无法通过 Swift 泛型获得预期的效果。我定义了一些通用函数,但对于特定情况,我想覆盖它们以提供附加功能。当我从非泛型方法/函数调用函数时,一切正常(当参数类型匹配时它使用特定版本,否则使用泛型版本),但是当我从泛型方法/函数调用函数时,它总是使用泛型函数的版本(绝不是特定版本)。
这是一个示例 Playground :
func printSomething <T> (something: T) {
println("This is using the generic version.")
println(something)
}
func printSomething(string: String) {
println("This is using the specific version.")
println(string)
}
func printSomeMoreThings <T> (something: T) {
printSomething(something)
}
class TestClass <T> {
var something: T
init(something: T) {
self.something = something
}
func printIt() {
printSomething(self.something)
}
}
printSomething("a")
println()
printSomeMoreThings("b")
let test = TestClass(something: "c")
println()
test.printIt()
这给出了以下输出:
This is using the specific version.
a
This is using the generic version.
b
This is using the generic version.
c
我希望它始终使用特定版本(因为它一直使用 String 参数调用 printSomething)。有没有一种方法可以在不使用特定字符串版本重载每个方法/函数的情况下执行此操作。特别是对于 Class 的情况,因为我不能为特定类型的 T 重载类方法?
最佳答案
由于您自己提到的原因,这目前无法实现(您不能为特定类型的 <T>
重载实例/类方法)。
但是,您可以在运行时检查类型并采取相应行动,而不是使用函数重载:
func printSomething<T>(something: T)
{
if let somestring = something as? String
{
println("This is using the specific version.")
println(somestring)
return
}
println("This is using the generic version.")
println(something)
}
除非您调用此函数数千次,否则对性能的影响应该可以忽略不计。
关于Swift 泛型方法应该使用重载的泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29717698/