What I want to accomplish is to pass the dynamic type of object as a parameter to generic function. I'm able to see the correct type I want with type(of:)
, but I'm unable to pass it as parameter, because in generic function I'm still getting the static type.
Here is an example what I want to do:
protocol SomeUsefulProtocol {}
struct MyType1: SomeUsefulProtocol {}
struct MyType2: SomeUsefulProtocol {}
let objects: [SomeUsefulProtocol] = [MyType1(), MyType2()]
let someClosureToWorkWithMyType: Any = { (object: MyType1) in
//Do some great things
}
func someMethod<T>(type: T.Type, object: Any) {
typealias ClosureType = (T) -> Void
if let closure = someClosureToWorkWithMyType as? ClosureType, let object = object as? T {
closure(object)
}
}
for object in objects {
someMethod(type: type(of: object), object: object)
}
Here i want closure someClosureToWorkWithMyType to be called when object has a type 'MyType1', but inside the method the type of object is the static type (SomeUsefulProtocol).