Skip to content

Instantly share code, notes, and snippets.

@Struki84
Last active December 3, 2015 17:01
Show Gist options
  • Save Struki84/8b2040658e3b6585d8a7 to your computer and use it in GitHub Desktop.
Save Struki84/8b2040658e3b6585d8a7 to your computer and use it in GitHub Desktop.
//Consider the scenario
class Foo {
var foBarVar: String?
init() {
foBarVar = "Test"
}
func someFunction() {
}
}
class Bar {
var barFoVar: String?
init() {
barFoVar = "Test"
}
func barFunction() {
}
}
//Create array with "Foo" and "Bar" classes
var array: [AnyClass] = []
array.append(Foo)
array.append(Bar)
//The question is, How to instantiate the clases from the array?
//Obviously this is not correct, just a sketch of the concept
for className in array {
let objectFromClass = className()
print(objectFromClass.foBarVar!)
}
@kviksilver
Copy link


protocol FooOrBar: class {
    init()
    var content: String { get }
}

class Foo: FooOrBar {
    var foBarVar: String
    required init() {
        foBarVar = "Test Foo"
    }
    var content: String {
        return foBarVar
    }
}

class Bar: FooOrBar {
    var barFoVar: String
    required init() {
        barFoVar = "Test Bar"
    }
    var content: String {
        return barFoVar
    }
}

var array: [FooOrBar.Type] = []
array.append(Foo)
array.append(Bar)

for className in array {
    let objectFromClass = className.init()
    print(objectFromClass.content)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment