Skip to content

Instantly share code, notes, and snippets.

@afarnham
Created June 26, 2015 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afarnham/1e80647c23eb36cf99f2 to your computer and use it in GitHub Desktop.
Save afarnham/1e80647c23eb36cf99f2 to your computer and use it in GitHub Desktop.
Dynamic instantiation of Swift classes conforming to a specific protocol
import UIKit
protocol FooProtocol {
init()
func description() -> String
}
class Bar : FooProtocol {
required init() {
}
func description() -> String {
return "Instance of \(self)"
}
}
let dict: [String : FooProtocol.Type] = ["class" : Bar.self]
if let klass = dict["class"] {
klass.init().description()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment