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

Rug*_*hel 6 generics overloading swift

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

这是一个示例游乐场:

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()
Run Code Online (Sandbox Code Playgroud)

这给出了以下输出:

This is using the specific version.
a

This is using the generic version.
b

This is using the generic version.
c
Run Code Online (Sandbox Code Playgroud)

我希望它始终使用特定版本(因为它始终使用 String 参数调用 printSomething)。有没有办法在不使用特定字符串版本重载每个方法/函数的情况下做到这一点。特别是对于 Class 的情况,因为我不能为特定类型的 T 重载类方法?

Vat*_*not 4

由于您自己提到的原因,目前无法实现这一点(您无法重载特定类型的实例/类方法<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)
}
Run Code Online (Sandbox Code Playgroud)

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

  • @RugenHeidbuchel:即使您有 ID,您也无法找到除您自己的错误报告之外的错误报告。您可能想到的是 OpenRadar,其中的错误是公开提交的。Apple 向您提供的 ID 用于引用_您_所做的特定错误报告。 (2认同)