Skip to content

Instantly share code, notes, and snippets.

@ptraca
Forked from Ben-G/DynamicInit.swift
Created December 19, 2018 19:33
Show Gist options
  • Save ptraca/0456ae6faa15f211e45e8e25232a4ed4 to your computer and use it in GitHub Desktop.
Save ptraca/0456ae6faa15f211e45e8e25232a4ed4 to your computer and use it in GitHub Desktop.
Dynamically create instance based on type in Swift
protocol Initializable {
init()
}
class A : Initializable {
var content:String
required init() {
content = "TestContent"
}
}
func createInstance<T where T:Initializable>(typeThing:T.Type) -> T {
return typeThing()
}
let a = createInstance(A)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment