2016-10-10 67 views
3

通用T迴流對於給定的泛型函數的迅速

func myGenericFunction<T>() -> T { }

我可以設置集類型是什麼類,通用將與

let _:Bool = myGenericFunction()

是有辦法做到這樣我不必在另一行分別定義一個變量?

例如:anotherFunction(myGenericFunction():Bool)

+1

你不能「明確地專門化一個通用函數」。我只是在做這方面的一些研究。它是在郵件列表中提出的,但似乎沒有任何地方:https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160523/018960.html –

回答

5

編譯器需要一些背景來推斷類型T。在 變量賦值,這可以用一個類型註釋或鑄造完成:

let foo: Bool = myGenericFunction() 
let bar = myGenericFunction() as Bool 

如果anotherFunction需要Bool參數然後

anotherFunction(myGenericFunction()) 

只是工作,T然後從參數類型推斷。

如果anotherFunction需要通用參數則 投再次工作:

anotherFunction(myGenericFunction() as Bool) 

一種不同的方法將是通過類型作爲參數 代替:

func myGenericFunction<T>(_ type: T.Type) -> T { ... } 

let foo = myGenericFunction(Bool.self) 
anotherFunction(myGenericFunction(Bool.self)) 
+0

感謝您的全面回答 – wyu