为什么我可以使用泛型来快速制作相同类型的要求?有什么办法吗?
发布时间:2020-12-14 04:42:53 所属栏目:百科 来源:网络整理
导读:好的,所以我有一些类定义如下: public final class ProcessInputType,OutputType,Memory 我想使该功能仅适用于InputType和 OutputType是完全相同的类型. 所以我尝试这样: extension Process where InputType == OutputType { } 但这会导致: Same-type req
好的,所以我有一些类定义如下:
public final class Process<InputType,OutputType,Memory> 我想使该功能仅适用于InputType和 extension Process where InputType == OutputType { } 但这会导致:
所以,我走了一段距离,并尝试这样做: 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 } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |