我可以在Swift中专门化一个通用的方法实现吗?

时间:2017-06-02 11:59:18

标签: swift generics swift3

我想以两种方式实现泛型函数,其中一种专门用于特定的泛型值,但到目前为止,我无法在Swift 3中表达这一点。

我的设置是这样的:

protocol Convertible {

    func convert<T>() -> Converted<T>
}

struct Unconverted: Convertible {

    func convert<T>() -> Converted<T> {
        return Converted<T>()
    }
}

struct Converted<T>: Convertible {

    func convert<T2>() -> Converted<T2> {
        return Converted<T2>()
    }
}

我希望在convert()上为Converted<T>添加T2 == T的特殊情况,对于let unconverted: Convertible = Unconverted() let converted: Convertible = unconverted.convert() as Converted<String> // double conversion to same generic type is ok, should ideally return self let convertedOk = converted.convert() as Converted<String> // re-conversion to another type is not ok and should fail let convertedFail = converted.convert() as Converted<Int> 的情况,以便实现以下行为:

struct Converted<T> {

    func convert<T2>() -> Converted<T2> {
        fatalError("already converted")
    }

    // error: Same-type requirement makes generic parameters 'T2' and 'T' equivalent
    func convert<T2>() -> Converted<T2> where T2 == T {
        return self
    }
}


struct Converted<T> {

    func convert<T2>() -> Converted<T2> {
        fatalError("already converted")
    }

    // method is never called, even when T2 == T
    func convert() -> Converted<T> {
        return self
    }
}


struct Converted<T> {

    func convert<T2>() -> Converted<T2> {
        // does not call the specialized method, even when T2 == T
        self.internalConvert(type: T2.self)
    }

    private func internalConvert<T2>(type: T2.Type) -> Converted<T2> {
        fatalError("already converted")
    }

    private func internalConvert(type: T.Type) -> Converted<T> {
        return self
    }
}

我尝试了以下方法,但没有一个能够实现:

document.addEventListener('DOMContentLoaded', function() {
    nameOfYourFunction();
});

有没有办法表达这个?

0 个答案:

没有答案