Initialize Class from Type in Swift

In this story we will see how we can initialize a Class from it’s Type

Photo by Clément H on Unsplash
class MyClass {}
func initializeObject<T>(fromType type: T.Type) -> T {    return ???}
var object1 = initializeObject(fromType: MyClass.self)
func initializeObject<T>(fromType type: T.Type) -> T {    //1
return T.init() //error
}
class MyClass {    required init() {}}
protocol Initializable {    //1
init
()
}
class MyClass: Initializable {    required init() {}}
func initializeObject<T: Initializable>(fromType type: T.Type) -> T {    return T.init() //No Error}
var object1 = initializeObject(fromType: MyClass.self)
var object2 = initializeObject(fromType: MyClass.self)
withUnsafePointer(to: &object1) {    print("object1 address: \($0)")}withUnsafePointer(to: &object2) {    print("object2 address: \($0)")}//prints:
object1 address: 0x000000012274c610
object2 address: 0x000000012274c618

iOS Engineer @ Advantage FSE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store