2016-12-02 41 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來 –

相關問題