Last active
December 3, 2015 17:01
-
-
Save Struki84/8b2040658e3b6585d8a7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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!) | |
} | |
Also, if you need to call the methods on them, after some light casting...
if let instance = instance as? Foo {
instance.someFunction()
} else if let instance = instance as? Bar {
instance.barFunction()
}
The problem is that I don't want to test each array element. I don't see the reason to test them if I know what types they are when I insert them in the array.
Your example is the way I do it now. I have a switch in my case.
for className in classNames {
switch classname {
case: "Foo"
Foo()
}
}
But now imagine if you have 20 classes that you have to manage like that. Its a tower of switch clasues, it would be much neater if i could just loop and to the work, since i know what classes are in the array.
I mean it's a normal paradigm in ObjC but hell in Swift
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
Perhaps: