I\'m looking to be able to pull out an instance of a UIView subclass from a Nib.
I\'d like to be able to call MyCustomView.instantiateFromNib() and have an instance
I believe the conditional expression you're looking for is topLevelObject.dynamicType == self
Combining this with unsafeBitCast
(which, by Apple's own documentation, "Breaks the guarantees of Swift's type system"), we can forcefully downcast topLevelObject
to self
's type. This should be safe because we already made sure that topLevelObject
is the same type as self
This is one way to get around the helper method using generics that Martin R described.
extension UIView {
class func instantiateFromNib() -> Self? {
let bundle = NSBundle.mainBundle().loadNibNamed("CustomViews", owner: nil, options: nil)
for topLevelObject in topLevelObjects {
if topLevelObject.dynamicType == self {
return unsafeBitCast(topLevelObject, self)
}
}
return nil
}
}
Note that Apple also says in their documentation for unsafeBitCast
:
There's almost always a better way to do anything.
So be careful!