Reputation: 4481
First, I know that this is the totally wrong syntax, but it illustrates what I want to do:
public func x(completion: CollectionType<MyClass> -> Void) {
}
Basically, what I'm trying to do is write a closure, that takes an object that supports the CollectionType protocol, and contains a collection of "MyClass" objects.
I don't care what kind of collection it is. If it supports CollectionType, then I should be able to get the "nth" object, or enumerate through the objects, etc. I've read that you can't pass generics in closure, so this may be impossible. If not, I'd be happy to hear how to do it.
Upvotes: 3
Views: 133
Reputation: 18308
You can use one of the types that adopt the AnyCollectionType
protocol to erase the type of the collection. For example:
class MyClass {}
func foo(completion: (AnyRandomAccessCollection<MyClass> -> Void)) {
completion(AnyRandomAccessCollection([MyClass()]))
}
foo { collection in
for item in collection {
print(item)
}
}
Upvotes: 3