How to use a generic class without the type argument in Swift?

二次信任 提交于 2019-12-05 04:24:19

Swift doesn’t yet support wildcard-style generics like Java does (i.e., Animal<?>). As such, a common pattern is to define a type-erased superclass, protocol (or wrapper) to enable such usage instead. For instance:

public class AnyAnimal {
    /* non-generic methods */
}

and then use it as your superclass:

public class Animal<T: YummyObject>: AnyAnimal {
    ...
}

Finally, use AnyAnimal in your non-generic code instead:

private static var animal: AnyAnimal!

Examples in the Swift Standard Library. For a practical example, see the KeyPath, PartialKeyPath, and AnyKeyPath classes hierarchy. They follow the same pattern I outlined above. The Collections framework provides even further type-erasing examples, but using wrappers instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!