Created
February 14, 2019 18:40
-
-
Save adamyanalunas/4b20e284c1a5820929a6cab49f23bc4d to your computer and use it in GitHub Desktop.
Generic Swift initializer of NSObjects with private init
This file contains hidden or 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
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