小编Bin*_*ing的帖子

如何在swift中检查一个对象是否是一种动态类类型?

我正在实现一个函数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 …
Run Code Online (Sandbox Code Playgroud)

swift

6
推荐指数
2
解决办法
646
查看次数

标签 统计

swift ×1