Skip to content

Instantly share code, notes, and snippets.

@adamyanalunas
Created February 14, 2019 18:40
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 adamyanalunas/4b20e284c1a5820929a6cab49f23bc4d to your computer and use it in GitHub Desktop.
Save adamyanalunas/4b20e284c1a5820929a6cab49f23bc4d to your computer and use it in GitHub Desktop.
Generic Swift initializer of NSObjects with private init
fileprivate extension NSObject {
/**
Initializes private init() subclasses of NSObject. Pure Swift classes
(and especially structs) will not work here.
```
// Given a class “PrivateInitClass” where `init()` is private
let somePrivateInitClassInstance = (PrivateInitClass.forcedInit() as PrivateInitClass)
```
- Note: Use this only for good.
*/
class func forcedInit<T>() -> T {
guard let bundleName = Bundle.main.infoDictionary?["CFBundleName"] else {
fatalError("Could not locate bundle name")
}
let className = String(describing: T.self)
let fullyQualifiedName = "\(bundleName).\(className)"
guard let classType = NSClassFromString(fullyQualifiedName) as? NSObject.Type else {
fatalError("Class “\(fullyQualifiedName)” does not subclass NSObject")
}
return (classType.init() as! T)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment