如何在Swift中使用没有类型参数的泛型类? [英] How to use a generic class without the type argument in Swift?
问题描述
我想将通用对象封装在另一个类中,而无需设置通用类型参数.我创建了一个基类Animal<T>
,并从中定义了其他子类.示例:
I want to encapsulate a generic object in another class without setting the generic type argument. I created a base Animal<T>
class and defined other subclasses from it. Example:
public class Animal<T: YummyObject> {
// Code
}
public class Dog: Animal<Bark> {
// Code
}
public class Cat: Animal<Meow> {
// Code
}
并在UITableView
扩展名下面定义了一个Animal
属性,不带类型参数:
and defined an Animal
property, without the type argument, in the UITableView
extension bellow:
extension UITableView {
private static var animal: Animal!
func addAnimal(animal: Animal) {
UITableView.animal = animal
}
}
但是这样做时出现以下编译错误:
but I get the following compile error when doing so:
对泛型类型
Animal
的引用需要<...>
中的参数.
Reference to generic type
Animal
requires arguments in<...>
.
这在 Java 中似乎可以正常工作.如何在 Swift 中完成同一件事?
This seems to work fine in Java. How can I accomplish the same thing in Swift as well?
推荐答案
Swift尚不支持 通配符样式的泛型 就像Java一样(即Animal<?>
).因此,常见的模式是定义类型擦除的超类,协议(或包装器)以启用这种用法.例如:
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 {
...
}
最后,在您的非通用代码中改为使用AnyAnimal
:
Finally, use AnyAnimal
in your non-generic code instead:
private static var animal: AnyAnimal!
Swift标准库中的示例.有关实际示例,请参见 KeyPath
, AnyKeyPath
类层次结构.它们遵循我上面概述的相同模式. 集合框架提供了进一步的类型擦除示例,但使用了包装器.
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.
这篇关于如何在Swift中使用没有类型参数的泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!