ofType
的函数,它会过滤掉所有给定类型的元素。以下是我的代码:
class Animal {}
class Mammal: Animal {}
class Monkey: Mammal {}
class Pig: Mammal {}
class Human: Mammal {}
extension Array {
func ofType<T>(_ metatype: T.Type) -> [T] {
return flatMap { type(of: $0) == metatype ? $0 as? T : nil }
// return flatMap { $0 as? T } // This is not working as the T is always the static type of the parameter, which is Animal in this example.
// return flatMap { $0 as? metatype } // This is not working either because of the grammar restriction.
}
}
let animals = [Monkey(), Pig(), Human(), Mammal(), Animal()]
func animalType() -> Animal.Type {
return Mammal.self
}
animals.ofType(animalType()).count // returns 1, expect to be 4.
在Objc中,我可以使用
isKindOf()
来检查一个对象是否是类或子类的实例。在Swift中也有类似的操作is
和as
,但是它们后面的类型应该是静态类型,而不是动态类型值(例如,我可以写is Mammal
,但不能写is Mammal.self
)。我也不能使用类型参数
T
,因为在这个例子中,T
等于Animal
,这不是我想要的。您有任何关于如何实现此功能的想法吗?
T
是什么? - SweeperT
是Animal
。 - Bing[Mammal]
是不可能的。 - Sweeper