好的,所以我有一些类定义如下:
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,Memory>
哪个最终只会在运行时失败,甚至在创建时失败,但是当具体类被触发以进行操作时.
有没有办法为不能编译的相同类型的泛型参数定义扩展或函数(导致编译时错误)?
更新:错过实现的一些细节会导致代码不可读,并且它们对于上下文并不重要
解决方法
在Swift 4及更高版本中,您可以编写:
public final class Process<InputType,Memory> { // ... } extension Process where InputType == OutputType { func bypass() -> Process<InputType,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,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 } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。