好的,所以我有一些类定义如下:
public final class Process<InputType, OutputType, Memory>
Run Code Online (Sandbox Code Playgroud)
我想使该功能仅适用于InputType和OutputType类型完全相同的情况.所以我尝试这样:
extension Process where InputType == OutputType { }
Run Code Online (Sandbox Code Playgroud)
但这会导致:
相同类型的要求使得通用参数
InputType
和OutputType
等效参数
所以,我走了一段距离,并尝试这样做:
func bypass<SameType>() -> Process<SameType, SameType, Memory> where OutputType == InputType {}
Run Code Online (Sandbox Code Playgroud)
但这会导致完全相同的错误.所以问题是为什么我不能以这样的方式定义泛型,即两个泛型类型将是等价的,因为这正是我想要的.我想定义仅适用于此情况的函数,如果不遵循此规则,则在编译时将失败.
所以现在我正在使用这样的东西:
public static func bypass<SameType>() -> Process<SameType, SameType, Memory>
Run Code Online (Sandbox Code Playgroud)
哪个最终只会在运行时失败,甚至在创建时失败,但是当具体类被触发以进行操作时.
有没有办法定义extension
或function
不能编译的相同类型的泛型参数(导致编译时错误)?
更新:错过实现的一些细节会导致代码不可读,并且它们对于上下文并不重要
在Swift 4及更高版本中,您可以编写:
public final class Process<InputType, OutputType, Memory> {
// ...
}
extension Process where InputType == OutputType {
func bypass() -> Process<InputType, OutputType, Memory> {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
原始答案(Swift 3):
即使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
}
}
Run Code Online (Sandbox Code Playgroud)