How to create an array of classes and instance objects with it in Swift?

I tried to ask this question earlier, but clearly did not express my question, so I will try again here. I also noticed a very similar sound question , but he asks for something completely different.

I have the following code:

class Base {
    func launch(code1: Int, code2: Int) { ... }
}

class A: Base {}
class B: Base {}
class C: Base {}

let classes = [A.self, B.self, A.self, B.self, C.self]
for cls in classes {
    let obj = ???
}

I would like to instantiate an object of type clsinside a loop and do something with it. As shown in the picture, I may have duplicates inside the array. What do I put in place ???to be able to create the right objects?

+4
source share
3 answers

, , required init, , Types, . A protocol, init, .

, , init .

- , .

protocol ZeroParamaterInit {
    init()
}

class Base : ZeroParamaterInit {
    func launch(code1: Int, code2: Int) {  }
    required init() {

    }
}

class A: Base {}
class B: Base {}
class C: Base {}

let classes : [ZeroParamaterInit.Type] = [A.self,B.self]
var instances : [Any] = []

for cls in classes {

    let instance = cls.init()
    instances.append(instance)

}

for instance in instances {

    if let test = instance as? A {
        print("A")
    }
    if let test = instance as? B {
        print("B")
    }
    if let test = instance as? C {
        print("C")
    }
}
+5

, : http://ijoshsmith.com/2014/06/05/instantiating-classes-by-name-in-swift/

Swift Obj ectFactory:

https://github.com/ijoshsmith/swift-factory

Swift. , , Objective-C, , Swift, Objective-C. , .

ObjectFactory :

let factory = ObjectFactory<MyClass>

MyClass, :

let myClass1 = factory.createInstance(className: "MyClassName")
0
import Foundation

class Base {}

class A: Base { var i: Int = 1 }
class B: Base { var i: String = "bravo" }
class C: Base { var i: Bool = true }

let classes = [A.self, B.self, A.self, B.self, C.self]

for cls in classes {
    var obj: Base? {
        switch cls {
        case is A.Type:
            return A()
        case is B.Type:
            return B()
        case is C.Type:
            return C()
        default:
            return nil
        }
    }
    dump(obj)
}


/*
▿ A
    ▿ Some: A #0
    - super: Base
    - i: 1
▿ B
    ▿ Some: B #0
    - super: Base
    - i: bravo
▿ A
    ▿ Some: A #0
    - super: Base
    - i: 1
▿ B
    ▿ Some: B #0
    - super: Base
    - i: bravo
▿ C
    ▿ Some: C #0
    - super: Base
    - i: true
*/

it's very close to r menke solution ...

0
source

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


All Articles