你能把对象的类型传递给函数吗?

时间:2018-02-16 23:16:55

标签: swift

我有一组不同类型的视图控制器。我希望能够检查数组是否包含各种类型。 换句话说,是否有任何方法可以简化以下代码

for item in theArray
{
   if item is ViewControllerTypeA
   {
     ...
   }
}
for item in theArray
{
   if item is ViewControllerTypeB
   {
     ....
   }
}
for item in theArray
{
   if item is ViewControllerTypeC
   {
     ....
   }
}

类似

func doesArrayContainType(T)
{
    for item in theArray
   {
       if item is T
       {
        ....
       }
   }
}

有没有什么方法可以使用泛型?如果是这样的话,没有关于泛型的教程或参考资料对我能看到的这种特殊情况有任何帮助。

2 个答案:

答案 0 :(得分:1)

是的,您可以将类型信息传递给方法

start

上述函数将为您提供目标序列中与您要搜索的类型匹配的元素列表。

如果编译器可以推断出结果类型,您可以使用或不使用extension Sequence { // gives you an array of elements that have the specified type func filterByType<T>(_ type: T.Type = T.self) -> [T] { return flatMap { $0 as? T } } } 参数:

type

答案 1 :(得分:0)

这里有三个不同的控制器。

class AViewController: UIViewController {}
class BViewController: UIViewController {}
class CViewController: UIViewController {}

一个带有文件夹数组和类型数组的函数。

func arrayOf<T: UIViewController>(_ array: [T], containsTypes types: [T.Type]) -> Bool {
    return array.contains { vc in types.contains { $0 === type(of: vc) as T.Type } }
}

该函数检查控制器的类型是否包含在给定类型的数组中。如果至少有一种类型,它将返回true。

let controllers = [
    AViewController(),
    BViewController(),
    CViewController()
]

print(arrayOf(controllers, containsTypes: [ AViewController.self, BViewController.self ]))
print(arrayOf(controllers, containsTypes: [ CViewController.self ]))
相关问题