Swift Generic with a Type First Known at Runtime

I have a question about fast and generics. What I'm trying to do is get an object with a common type. But first, I know the type at runtime. But quickly get to the place.

New edited block:

Maybe I can do this with the class name? I have a class name as a string. I got it through the mirror. Can I create a shared instance with this class name in a string?

let classname: String = "ClassA"
let firstA: a<classname> = a<classname>()
//            ^^^^^^^^^      ^^^^^^^^^
//            what to put here???          

New edited block end:

I have two classes with common types:

This is the protocol that my type should implement:

protocol ToImplement {
    func getTypeForKey(key: String) -> NSObject.Type
}

This is the class that I use for the first first type:

class MyClass: ToImplement {
    func getTypeForKey(key: String) -> NSObject.Type {
        if key == "key1" {
            return UIView.self
        } 
        else {
            return UIButton.self
        }
    }
}

this is my first class with a generic type:

class a<T:ToImplement> {
    func doSomethingWith(obj: T) -> T {

        // the next part usually runs in an iteration and there can be
        // a lot of different types from the getTypeForKey and the number
        // of types is not known

        let type = obj.getTypeForKey("key1")
        let newA: a<type> = a<type>()       // how could I do this? To create a type I do not know at the moment because it is a return value of the Object obj?
        //          ^^^^      ^^^^
        //          what to put here???


        return obj
    }
}

and thatโ€™s how I will use it:

let mycls: MyClass = MyClass()
let firstA: a<MyClass> = a<MyClass>()
firstA.doSomethingWith(mycls)

: a , ? ?

, . - :

let someA: a<instance.type> = a<instance.type>()

!

+4
1
let type = obj.getType

, type - NSObject.Type. NSObject init(),

let obj = type.init()  // obj is a NSObject (or subclass)
return obj

, , , getType(), init().

- :

protocol ToImplement {
    typealias ObjType: NSObject
}

:

func makeAnObject<T: ToImplement>(obj: T) -> T.ObjType {
    return T.ObjType()
}

.

+1
source

Source: https://habr.com/ru/post/1623375/


All Articles