Skip to content

Instantly share code, notes, and snippets.

@fernandomatal
Created March 19, 2019 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fernandomatal/bfe50fbc4377845de54efb637ef0b722 to your computer and use it in GitHub Desktop.
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.
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
}
}
@fernandomatal
Copy link
Author

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.

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