vendredi 2 mars 2018

Pass dynamic type as parameter

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 MyType: SomeUsefulProtocol {}

let object: SomeUsefulProtocol = MyType()

let someClosureToWorkWithMyType: Any = { (object: MyType) 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)
    }
}

And what I want is to pass the MyType and object as parameters for someMethod. I have tried following:

someMethod(type: type(of: object), object: object)

but in someMethod I'm still getting the static type of object (i.e., SomeUsefulProtocol).





Aucun commentaire:

Enregistrer un commentaire