[英]How to pass a Type as a parameter in Swift
I have a dictionary of objects and what I would like to do is go through the data set and return an array of objects that conform to a given protocol. 我有一个对象字典,我想要做的是遍历数据集并返回符合给定协议的对象数组。 I am having issues with the syntax for passing in a desired protocol:
我遇到传递所需协议的语法问题:
func getObjectsThatConformTo<T>(conformance: T.Type) -> [AnyClass]{
var returnArray: [AnyClass] = []
for(myKey, myValue) in allCreatedObjects{
if let conformantObject = myValue as? conformance{
returnArray.append(conformantObject)
}
return returnArray
}
The error I am seeing is 'conformance' is not a type 我看到的错误是“一致性”不是一种类型
Thank you for your help and time 谢谢你的帮助和时间
I think this should work: 我认为这应该有效:
func getObjectsThatConformToType<T>(type:T.Type) -> [T]{
var returnArray: [T] = []
for(myKey, myValue) in allCreatedObjects{
if let comformantModule = myValue as? T {
returnArray.append(comformantModule)
}
}
return returnArray
}
While you could write a generic-ed method that filters through an array and sees which things in the array are a given type, this problem screams for the use of filter
. 虽然您可以编写一个通用的方法来过滤数组并查看数组中的哪些内容是给定的类型,但是这个问题对于使用
filter
感到尖叫。
Example: 例:
var dict: [String: AnyObject] = [:]
// Populate dict with some values
let strings = dict.values.filter { return $0 is String }
Wrapped in a function that takes type: 包含在一个带类型的函数中:
func getObjectsThatConformTo<T>(array: [Any], conformance: T.Type) -> [T]? {
return array.filter { return $0 is T } as? [T]
}
Explanation: Filter is a method on Array which returns a subset of the array based on a test. 说明:Filter是Array上的一个方法,它根据测试返回数组的子集。 In this case our test is 'is the element a String?'
在这种情况下,我们的测试'是元素是一个字符串吗?' the filter method accepts a closure with one parameter, the element to be tested, above referred to with $0.
filter方法接受一个带有一个参数的闭包,即要测试的元素,上面用$ 0引用。
Read up on filter here: https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/ 阅读过滤器: https : //www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.