为什么我可以使用泛型来快速制作相同类型的要求?有什么办法吗?

时间:2016-12-02 22:06:20

标签: swift generics

好的,我有一些类定义如下:

public final class Process<InputType, OutputType, Memory>

我想使该功能仅适用于InputType和 OutputType是完全相同的类型。 所以我尝试这样:

extension Process where InputType == OutputType { }

但这会导致:

  

相同类型的要求使通用参数InputType和   等同于OutputType

那么我走得有点远,试着这样做:

func bypass<SameType>() -> Process<SameType, SameType, Memory> where OutputType == InputType {}

但这会导致完全相同的错误。 所以问题是为什么我不能以这样的方式定义泛型,即两个泛型类型将是等价的,因为这正是我想要的。我想定义仅适用于这种情况的函数,如果不遵循此规则,则在编译时会失败。

所以现在我正在使用这样的东西:

public static func bypass<SameType>() -> Process<SameType, SameType, Memory>

哪个最终会在运行时失败,甚至在创建时失败,但是当触发具体类进行操作时。

有没有办法为那些不能编译的相同类型的泛型参数定义extensionfunction(导致编译时错误)?

更新:错过实现的一些细节会导致代码不可读,并且它们对上下文不重要

1 个答案:

答案 0 :(得分:6)

Swift 4及更高版本中,您可以写:

public final class Process<InputType, OutputType, Memory> {
    // ...
}

extension Process where InputType == OutputType {
    func bypass() -> Process<InputType, OutputType, Memory> {
        // ...
    }
}

原始答案(Swift 3):

即使some changes在Swift 4中出现,也不能约束泛型类的类型。但是,您可以在协议上约束类型。您可以制定只有Process符合的协议:

protocol ProcessProtocol {
    // I haven't found a way to name these associated type identically to
    // those in the class. If anyone discover a way, please let me know
    associatedtype IT
    associatedtype OT
    associatedtype MT
}

final public class Process<InputType, OutputType, MemoryType>: ProcessProtocol {
    typealias IT = InputType
    typealias OT = OutputType
    typealias MT = MemoryType

    // your code
}

// Note that this is an extension on the protocol, not the class
extension ProcessProtocol where IT == OT {
    func foo() {
        // this function is only available when InputType = OutputType
    }
}
相关问题