Swift - 检查对象是否属于给定类型(其中类型已作为函数参数传递)

时间:2018-03-25 08:43:36

标签: ios swift

所以我有一个充满对象的数组,这些对象都继承自基类MyBaseClass。比如,有这些子类:

SubclassA : MyBaseClass
SubclassB : MyBaseClass
SubclassC : MyBaseClass
SubclassD : MyBaseClass

现在我想要一个函数来过滤数组,并且只包含给定子类的类型的对象:

func myFilter<T: MyBaseClass>(objectType: T.Type) -> [MyBaseClass] {
   ...
   for object in myArray {
       // include, if object is of type `objectType`
   }

   return filteredArray
}


// Example call (that's what I think how it should be called)
let filteredArray = myFilter(objectType: SubclassD.self)

我该怎么做?我试过了:

object is objectType // XCode: "Use of undeclared type itemType"
type(of: object) == objectType // returns always false, as it doesn't check for subclasses I think
object as objectType // XCode: "Use of undeclared type itemType"

当我想检查IntString或其他什么时,这通常有效。但它不在这里工作。我做错了什么或者我是否误解了一些概念?

任何帮助表示赞赏!感谢

1 个答案:

答案 0 :(得分:1)

我不知道你要去哪儿myArray。您可能需要为MyBaseClass创建Array的扩展。像这样:

extension Array where Element: MyBaseClass {
  func myFilter<T: MyBaseClass>(objectType: T.Type) -> [T] {
    var filteredArray: [T] = []
    for object in self {
      if let object = object as? T {
        filteredArray.append(object)
      }
    }

    return filteredArray
  }
}

然后你可以打电话:

// Example call
let array = [SubclassA(), SubclassA(), SubclassC(), SubclassD()]
array.myFilter(objectType: SubclassD.self) // == [SubclassD()]

编辑: 如果您希望返回类型myFilter只是MyBaseClass并且您不想更改原始数组,那么简单的解决方案就是:

array.filter { $0 is SubclassD }