Created
March 19, 2019 06:38
-
-
Save fernandomatal/bfe50fbc4377845de54efb637ef0b722 to your computer and use it in GitHub Desktop.
Get class with special string identifier on Runtime. Handful if you need to load dynamically a class according to some runtime value.
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
struct RuntimeClass { | |
private static var appName: String { | |
return Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String | |
} | |
enum Class { | |
case Example | |
fileprivate var name: String { | |
switch self { | |
case .Example: | |
return "Example" | |
} | |
} | |
} | |
enum RuntimeClassErrors: Error { | |
case ClassNotFound | |
} | |
/// Returns the class needed according to the identifier. Casting of class should be done from the receiver. Throws error in case a market file with that name doesn't exist. | |
static func getRuntimeClass(class runtimeClass: Class, identifier: String) throws -> AnyClass? { | |
let className = appName + "." + runtimeClass.name + identifier | |
guard let runtimeClass = NSClassFromString(className) else { | |
throw RuntimeClassErrors.ClassNotFound | |
} | |
return runtimeClass | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an example of how to use it:
do { let exampleType = try RuntimeClass. getRuntimeClass(class: MarketFile.File.Example, identifier: "MX") as? Example.Type exampleClass = exampleType?.init() } catch { fatalError("\(error)") }
In this case, Example is a protocol that gets implemented by different classes named ExampleMX, ExampleUS, ExampleES, etc.