Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
@muhasturk

This comment has been minimized.

Copy link

@muhasturk muhasturk commented Apr 5, 2019

Swift 5.x

protocol Initializable {
    init()
}

class A : Initializable {
    var content:String
    
    required init() {
        content = "TestContent"
    }
}

func createInstance<T>(typeThing:T.Type) -> T where T:Initializable {
    return typeThing.init()
}

let a = createInstance(typeThing: A.self)
@rahul-inspired-iosdeveloper

This comment has been minimized.

Copy link

@rahul-inspired-iosdeveloper rahul-inspired-iosdeveloper commented Jun 10, 2020

Do you know how we can do this in objective-c

@akingdom

This comment has been minimized.

Copy link

@akingdom akingdom commented Sep 12, 2020

Do you know how we can do this in objective-c

id instance = [[NSClassFromString(@"ClassName") alloc] init];

https://developer.apple.com/documentation/foundation/1395135-nsclassfromstring

Remember to manage you memory as needed! There are other ways to create an instance but this is a common one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment