2017-09-27 80 views
1

協議我想使用SWIFT一般如下代碼顯示:可以投噸至comform在迅速

func handle<T>(data: Data, with type: T.Type) { 
    if type is B.Type { 
     handleOne(data: data, with: type) //error here: In argument type 'T.Type', 'T' does not conform to expected type 'B' 
     // cast T comform B? 
    } else { 
     handleTwo(data: data) 
    } 
} 

func handleOne<T>(data: Data, with type: T.Type) where T:B { 

} 

func handleTwo(data: Data) { 

} 

...

protocol B { 
    ... 
} 

B是一個協議,我可以打電話handleOnehandle ?可以鑄造T通知B

+0

編譯器**不**足夠聰明,知道'如果類型是B.Type'是TRUE;然後類型實際上是'B'型。由於'B'類型是'handleOne'函數的一個要求,所以這會失敗! – Honey

+0

我不這麼認爲,我在Xcode9 swift4中試過,使用'struct A:B {}','handle(data:Data(),with:A.self)'',如果type是B.Type'是'true',你可以試試這個 –

回答

2

將類型作爲參數傳入是沒有必要的,因爲它可以從對象本身檢索。該is類型檢查操作的工作對象和檢查的情況下,對類型名稱:

protocol A {} 

protocol Data {} 

func handle (data: Data) { 
    if data is A { 
    print("Handled A.") 
    } else { 
    print("Handled something else.") 
    } 
} 

struct AStruct: Data, A {} 

handle(data: AStruct()) // Handled A. 
+0

在我的問題中,'handleOne'需要參數'.Type'。 –

+0

這應該工作:'FUNC處理(數據:T){ 如果數據是一個十 handleOne(數據:數據,具有:類型(:數據)) }其他{ 打印( 「已處理別的事情。」 ) } }' –

+0

您也可以使用T.self而不是type(of:data)。 –