你如何检查一个对象是否是一个类型数组?
How can you check if an object is one of an array of types?
给定以下数组:
let ignoredViewControllerTypes:[UIViewController.Type] = [
ViewControllerB.self,
ViewControllerC.self
]
let allViewControllers = [
viewControllerAInstance,
viewControllerBInstance,
viewControllerCInstance,
viewControllerDInstance
]
过滤 allViewControllers
以排除 ignoredViewControllerTypes
中的那些类型的语法是什么?
我已经试过了,但是没用:
let filteredControllers = allViewControllers.filter{ !ignoredViewControllerTypes.contains([=11=].self) }
那我错过了什么?
这应该有效:
let filteredControllers = allViewControllers.filter { viewController in
!ignoredViewControllerTypes.contains(where: { type(of: viewController) == [=10=] })
}
让我们将其分解为子任务:
您想检查是否允许使用控制器
func isAllowed(_ controller: UIViewController) -> Bool {
return !ignoredViewControllerTypes.contains { controller.isKind(of: [=10=]) }
}
您要过滤一组控制器:
let filteredControllers = allViewControllers.filter(isAllowed)
注意 isAllowed
也会过滤被忽略的控制器的子类,如果你想要精确的类型匹配那么你应该使用@dan 的答案。
作为奖励,因为我喜欢函数式编程,您可以通过将 isAllowed
转换为 high-order 函数来使它成为一个纯粹而灵活的函数:
func doesntBelong(to prohibitedClasses: [AnyClass]) -> (AnyObject) -> Bool {
return { obj in
prohibitedClasses.contains { obj.isKind(of: [=12=]) }
}
}
,可以这样使用:
let filteredControllers = allViewControllers.filter(doesntBelong(to: ignoredViewControllerTypes))
给定以下数组:
let ignoredViewControllerTypes:[UIViewController.Type] = [
ViewControllerB.self,
ViewControllerC.self
]
let allViewControllers = [
viewControllerAInstance,
viewControllerBInstance,
viewControllerCInstance,
viewControllerDInstance
]
过滤 allViewControllers
以排除 ignoredViewControllerTypes
中的那些类型的语法是什么?
我已经试过了,但是没用:
let filteredControllers = allViewControllers.filter{ !ignoredViewControllerTypes.contains([=11=].self) }
那我错过了什么?
这应该有效:
let filteredControllers = allViewControllers.filter { viewController in
!ignoredViewControllerTypes.contains(where: { type(of: viewController) == [=10=] })
}
让我们将其分解为子任务:
您想检查是否允许使用控制器
func isAllowed(_ controller: UIViewController) -> Bool { return !ignoredViewControllerTypes.contains { controller.isKind(of: [=10=]) } }
您要过滤一组控制器:
let filteredControllers = allViewControllers.filter(isAllowed)
注意 isAllowed
也会过滤被忽略的控制器的子类,如果你想要精确的类型匹配那么你应该使用@dan 的答案。
作为奖励,因为我喜欢函数式编程,您可以通过将 isAllowed
转换为 high-order 函数来使它成为一个纯粹而灵活的函数:
func doesntBelong(to prohibitedClasses: [AnyClass]) -> (AnyObject) -> Bool {
return { obj in
prohibitedClasses.contains { obj.isKind(of: [=12=]) }
}
}
,可以这样使用:
let filteredControllers = allViewControllers.filter(doesntBelong(to: ignoredViewControllerTypes))