我来自C++,我对Swift中的泛型函数有点困惑。Swift中的泛型函数
在C++中,我能做到这一点:
class Entity
{
template <typename T>
T *getComponent()
{
return (T *)(listComponent_[typeid(T).name()]);
}
};
,我可以做到这一点,从获取特定Component
我Entity
Entity().getComponent<LifeComponent>();
我想重现此斯威夫特,但我无法弄清楚如何实现它。
在Swift中,我必须为我的函数定义一个参数来确定我的类型。
在斯威夫特:
class Entity
{
func get<T>() -> T
{
return ??
}
}
我希望能够做到:
Entity().get<LifeComponent>()
你能帮助我吗?
[谷歌,先打:官方文档(https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26 -XID_278)。 [谷歌,第三击:教程](http://www.codingexplorer.com/generic-functions-in-swift/)。您不必“弄清楚”这一点:使用Google并阅读文档就足够了。 – 2014-10-20 13:11:53
我知道如何创建泛型函数,以及如何使用它。我只想知道是否有一种方法可以像C++中那样在Swift中传入一个类型。 – cappie013 2014-10-20 13:21:32