How to pass type as parameter in Swift

I have a dictionary of objects, and I would like to do this through a dataset and return an array of objects that conform to this protocol. I am having problems with the syntax for passing in the 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 see is a "match", not a type

Thank you for your help and time.

+7
ios iphone swift protocols
source share
2 answers

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 } 
+14
source share

While you can write a generic method that filters through an array and sees which things in the array are a given type, this problem yells about using 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 a type:

 func getObjectsThatConformTo<T>(array: [Any], conformance: T.Type) -> [T]? { return array.filter { return $0 is T } as? [T] } 

Explanation: A filter is a method in an array that returns a subset of the array based on the test. In this case, our test is "an element of a String?" the filter method accepts a closure with one parameter, the checked element, above which $ 0 is denoted.

Read here: https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/

+1
source share

All Articles