0

I'm trying to implement a UIViewController extensions that gets the first child view controller with a certain type.

I tried:

func getChildViewController(#type:UIViewController.Type) -> UIViewController? {
    for vc:UIViewController in self.childViewControllers as [UIViewController] {
        if vc is type { //<-- 'type is not a type'
            return vc
        }
    }
    return nil
}

And:

func getChildViewController(#type:Type) -> UIViewController? { // "Type", doesn't exist
    for vc:UIViewController in self.childViewControllers as [UIViewController] {
        if vc is type {
            return vc
        }
    }
    return nil
}

And this (partially derived from How to pass a class type as a function parameter):

func getChildViewController<T>(#type:T.Type) -> UIViewController? {
    for vc:UIViewController in self.childViewControllers as [UIViewController] {
        if vc is type { //<-- 'type is not a type'
            return vc
        }
    }
    return nil
}

Nothing works! How can I do this? Thanks!

Community
  • 1
  • 1
User
  • 31,811
  • 40
  • 131
  • 232

1 Answers1

2

In your last example, change

if vc is type 

to

if vc is T

T is the type you’re looking for, whereas T.Type is a metatype giving information about the type T. All you’re really using T.Type for is to fix T to be the type that you want when you call getChildViewController.

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
  • Ohh, ok, that's somehow weird. I expected the variable ("type") to be the type. In Java for example it's possible to do this: `void foo(Class> a) { String b = ""; if (a.isInstance(b)) {} }` – User Jan 03 '15 at 22:08
  • Maybe I can't judge this correctly, but this syntax has something counterintuitive. Anyways, it works, thanks! – User Jan 03 '15 at 22:22