Swift 泛型方法应该使用重载的泛型函数

Swift generic method should use overloaded generic function

我无法通过 Swift 泛型获得预期的效果。我定义了一些通用函数,但对于特定情况,我想覆盖它们以提供附加功能。当我从非通用 method/function 调用函数时一切正常(当参数类型匹配时它使用特定版本,否则使用通用版本),但是当我从通用 method/function 调用函数时它始终使用函数的通用版本(从不使用特定版本)。

这是一个示例游乐场:

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)。有没有一种方法可以在不使用特定字符串版本重载每个 method/function 的情况下执行此操作。特别是对于 Class 的情况,因为我不能为特定类型的 T?

重载 class 方法

由于您自己提到的原因,目前无法实现(您不能为特定类型的 <T> 重载 instance/class 方法)。

但是,您可以在运行时检查类型并采取相应行动,而不是使用函数重载:

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)
}

除非您调用此函数数千次,否则对性能的影响应该可以忽略不计。