Create an instance of a class based on a function argument

Suppose I have three classes:

import Foundation

class A {

    init() {
      print("A")
    }

}

class B {

    init() {
        print("B")
    }

}

class C {

    init() {
       print("C")
    }
}

I want to dynamically pass a string ("A", "B" or "C") as an argument to a function, and then create an instance of the class that I passed inside the body of this function. Is it possible? How?

I tried this (and other options) but no luck:

func test(c:AnyObject){
    let _class = c()
    //...
}

test(c:A)

[UPDATE] This question may be no different from the one suggested by @Code Different, but this question is old and there have been so many changes in the language that you need to try any proposed solution before you find the one that works for today day

+4
source share
1 answer

, BaseClass. , , BaseClass.

.

, :

class BaseClass { }

class A: BaseClass { ... }
class B: BaseClass { ... }
class C: BaseClass { ... }

func test(type: BaseClass.Type) {
    let someObject = type.init()
    // You can cast the object if required
}

test(type: A.self) // creates an object of class A
test(type: B.self) // creates an object of class B

: , test. , test .

: , , , :

protocol SomeProtocol: class {
    init()
    func someFunction()
}

class A {
    required init() {
        print("A")
    }
}

extension A: SomeProtocol {
    func someFunction() {
        print("Some function of A")
    }
}

class B {
    required init() {
        print("B")
    }
}

extension B: SomeProtocol {
    func someFunction() {
        print("Some function of B")
    }
}

class C {
    required init() {
        print("C")
    }
}

extension C: SomeProtocol {
    func someFunction() {
        print("Some function of C")
    }
}

func test(someType: SomeProtocol.Type) {
    let someObject: SomeProtocol = someType.init()
    someObject.someFunction()
}

test(someType: A.self) // creates an object of class A
test(someType: B.self) // creates an object of class B
+1

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


All Articles