2016-11-24 109 views
2

我想了解泛型文化斯威夫特所以我写了一个小例子。但它不编译。Associatedtype斯威夫特3

错误:通用参数“P”无法推断 我无法理解,因为我做错了。

protocol Protocol_1 { 
    associatedtype T 
} 

protocol Protocol_A {} 
struct SomeStruct_2: Protocol_A {} 

struct SomeStruct_1: Protocol_1 { 
    typealias T = Protocol_A 
} 


let struct1 = SomeStruct_1() 
testFunction(t: struct1) // *Generic parameter 'P' could not be inferred* 

func testFunction<P: Protocol_1>(t: P) where P.T : Protocol_A { 

} 
+1

[协议不符合自己(http://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself)的斯威夫特,所以你不能用'Protocol_A'作为一种类型符合'Protocol_A'。 – Hamish

回答

2

P.T在testFunction中不能符合Protocol_A,但可以检查它是否等于Protocol_A。

func testFunction<P: Protocol_1>(t: P) where P.T == Protocol_A { 
}