2016-03-28 98 views

回答

1

注意下面的編譯:

protocol Foo { 
    associatedtype A 
} 

struct Container<F: Foo> { 

    func f(a: F.A) { } 
} 

然而,在的情況下:

struct Container<F: Foo> { 

    func f<A : F.A>(a: A) { } // error: inheritance from non-protocol, non-class type 
} 

...類型F.A完全不受約束,因此它很可能是,比如說,一個Int,你不能從:語法繼承或符合。

如果你真的需要比(a: F.A)一個更通用的解決方案,然後沿着這些路線的東西可能會做到這一點:

protocol Bar { } 

protocol Foo { 
    associatedtype A : Bar 
} 

struct Container<F: Foo> { 

    func f<A : Bar>(a: A) { } 
} 

現在,您可以表達對使用Bar協議a參數的任何預期。

更妙的是,你可能能夠實現方法的Foo擴展:

protocol Foo { 
    associatedtype A 

    func f(_: A) // if you want this to be a requirement 
} 

extension Foo /* where A is constrained so you can do something with it */ { 

    func f(a: A) { } 
} 
+0

在我的使用情況下,'Container'方法'F'必須被約束的Foo'子類類型。也就是說,它必須是「Foo.A」類型或子類。當你說F.A沒有約束是問題時,我不確定你是對的。畢竟,如果我們使'associatedtype A:Bar','func f (a:A){}'仍然失敗。 – Stephen

+0

我注意到了我們的片段之間的區別。我在迴應你引用'F.A型完全無約束'的地方作爲錯誤的原因。即使有限制,結果也是一樣的。爲什麼不能將關聯的類型用作約束? – Stephen

相關問題