2

Consider the following code which loads a view based on a nib/xib with the same name as the class...

extension UIView
{
    static func loadFromNib<T:UIView>() -> T
    {
        let nibName = String(T)
        let bundle = NSBundle(forClass: self)

        return bundle.loadNibNamed(nibName, owner: nil, options: nil)[0] as! T
    }
}

In order to use it, you need to do this...

let view:SomeView = UIView.loadFromNib()

This way, T is inferred to be SomeView from the variable it's being assigned to.

However, I'm trying to get it down to this, if possible...

let view = SomeView.loadFromXib()

...where the type SomeView is inferred from the class loadFromNib is called on, but I can't figure out how to define the constraint for T relative to self to support that.

So is this possible?

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
  • I strongly assume that the linked-to Q&A is what you are looking for. Otherwise let me know and I'll reopen the question. – Martin R Aug 23 '16 at 18:04
  • It isn't. In that example, Self refers to UIView. I want whatever refers to SomeView or SomeOtherView provided they are both classes of UIView, which is why I used the generic version. – Mark A. Donohoe Aug 23 '16 at 18:07
  • 1
    Did you try it? With that extension method, `let someView = SomeView.instantiateFromNib()` gives you an instance of `SomeView`, and the type is inferred correctly as `SomeView`. – Martin R Aug 23 '16 at 18:08
  • 1
    I have updated the linked-to answer to make it (hopefully) more clear. – Martin R Aug 23 '16 at 18:11
  • 1
    I stand corrected. It does work as you stated. I have to say that was actually a pretty clever use of a private generic like that to get around not being able to cast to Self. Kudos, and thanks! – Mark A. Donohoe Aug 23 '16 at 19:09
  • You are welcome, and thanks for confirming it. – Martin R Aug 23 '16 at 19:11
  • Hey... you may want to explain how you're using that private generic method to get around not being able to explicitly cast to type Self. That's a pretty neat trick and what I missed when I first looked at it. Your updated explanation shows that it works, but doesn't explain the 'why' which to me is the really interesting part. – Mark A. Donohoe Aug 23 '16 at 23:59

0 Answers0