natecraft1
natecraft1

Reputation: 2836

Dynamic Type checking confusion Swift

I have a function that takes a parameter vcType: UIViewController.Type and I'm trying to make the check

if getTopmostViewController() is vcType {
  // do stuff
}

But I'm an error "vcType is not a type". I'm not sure what the issue is or whether there is a better way to do this.

Upvotes: 0

Views: 199

Answers (2)

Eppilo
Eppilo

Reputation: 773

Try replacing:

getTopmostViewController() is vcType

With:

getTopmostViewController().dynamicType == vcType

EDIT: This would only work to check the exact type. If the the controller returned by getTopmostViewController() is a descendant of vcType, then false would be returned.

Upvotes: 3

rob mayoff
rob mayoff

Reputation: 385500

Maybe you want something like this:

if getTopmostViewController().isKindOfClass(vcType.dynamicType) {
    // do stuff
}

Above, vcType is an instance of some class, and it's checking whether getTopmostViewController() returns an instance of the same class (or a subclass).

Or maybe you really want to write a function like this:

func doStuffIfTopMostViewControllerHasType<VCType: UIViewController>(_: VCType.Type) {
    if getTopmostViewController() is VCType {
        // do stuff
    }
}

Which you then call like this:

doStuffIfTopMostViewControllerHasType(MyViewController.self)

Note that I'm passing the MyViewController class itself, not an instance of MyViewController.

Upvotes: 2

Related Questions