Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Last active May 27, 2023 13:30
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save Ben-G/cb1708b1068d2bc5916f to your computer and use it in GitHub Desktop.
Save Ben-G/cb1708b1068d2bc5916f 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)
@muhasturk
Copy link

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

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

@akingdom
Copy link

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