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!)
}
@vladimirkolbas
Copy link

Perhaps:

for className in array {
    var instance: AnyObject!

    if className.self == Foo.self {
        instance = Foo()
    } else if className.self == Bar.self {
        instance = Bar()
    }

    if instance is Foo {
        print("Foo")
    } else {
        print("Bar")
    }
}

@vladimirkolbas
Copy link

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()
    }

@Struki84
Copy link
Author

Struki84 commented Dec 1, 2015

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

@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