【发布时间】:2018-07-10 04:35:55
【问题描述】:
我正在实现一个名为 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() 来检查对象是类的实例还是子类。 swiftis和as也有类似的操作,但是后面的类型应该是静态类型,而不是动态类型值(比如我可以写is Mammal,但不能写is Mammal.self)。
我也不能使用类型参数T,因为在本例中,T 等于Animal,这不是我想要的。
你知道如何实现这个功能吗?
【问题讨论】:
-
你不知道在编译时要过滤掉什么类型吗?
-
@Sweeper No. 类型仅在运行时确定。
-
那么编译器怎么可能知道
T是什么? -
@Sweeper 编译器只知道参数的静态类型,本例中
T为Animal。 -
没错!所以我的意思是返回
[Mammal]是不可能的。
标签: swift