2016-12-02 74 views
5

行,所以我有这样定义了一些类:为什么我可以用泛型快速制作相同类型的需求?有什么办法吗?

public final class Process<InputType, OutputType, Memory> 

,我想借此让该功能仅适用于情况下的inputType和 输出类型是完全相同的类型。 于是,我就这样像这样:

extension Process where InputType == OutputType { } 

但是,这会导致:

相同类型的要求使得泛型参数InputTypeOutputType相当于

于是我”已经走了很远,并试图这样做:

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

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

所以现在我使用的是这样的:

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

这将最终只能在运行时失败,而不是创建即使但当具体的类被触发的行动。

有没有什么办法可以为extensionfunction定义相同类型的通用参数,而这些通用参数只是不编译(导致编译时错误)?

更新:实现的一些细节被遗漏的原因会使得代码不可读的,他们是不是上下文

回答

6

斯威夫特4和更高关键,你可以写:

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

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

最初的回答(雨燕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 
    } 
} 
+0

感谢这个完全解决我的问题,直到雨燕4来 –

相关问题