Last active
May 27, 2023 13:30
-
-
Save Ben-G/cb1708b1068d2bc5916f to your computer and use it in GitHub Desktop.
Dynamically create instance based on type in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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.