好的,所以我定义了一些这样的类:
public final class Process<InputType, OutputType, Memory>
而且我想让该函数仅适用于 InputType 和 OutputType 是完全相同的类型。 所以我像这样尝试过:
extension Process where InputType == OutputType { }
但这会导致:
Same-type requirement makes generic parameters
InputType
andOutputType
equivalent
然后我走得有点远,并尝试这样做:
func bypass<SameType>() -> Process<SameType, SameType, Memory> where OutputType == InputType {}
但这会导致完全相同的错误。 所以问题是为什么我不能以两种泛型类型等效的方式定义泛型,因为这正是我想要的。我想定义仅适用于这种情况的函数,如果不遵守此规则,它将在编译时失败。
所以现在我正在使用这样的东西:
public static func bypass<SameType>() -> Process<SameType, SameType, Memory>
这最终只会在运行时失败,甚至不会在创建时失败,而是在触发具体类执行操作时失败。
有没有办法为相同类型的泛型参数定义extension
或function
而不会编译(导致编译时错误)?
更新:遗漏了一些实现细节,因为这会使代码不可读,而且它们对上下文并不重要
最佳答案
在 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 中出现。但是,您可以在协议(protocol)上约束类型。您可以创建一个只有 Process
符合的协议(protocol),如下所示:
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
}
}
关于swift - 为什么我可以用泛型在 swift 中提出相同类型的要求?有什么办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941566/