简体   繁体   中英

Swift compare two MetaTypes?

I need to test to see if a Type I'm passing to a function is of a certain class or not

func doSomething<T> (type: T.Type) -> T {

   // Check to see if type is the same as Raw type?

   if type == Raw.self { } // Doesn't work, Compile error

   if type is? Raw.self { } // Doesn't work, Compile error
}

@objc class Raw {

}

Function overloading would be my first choice, but to answer the question; either use NSStringFromClass , or the following:

@objc class Raw {

}

func doSomething<T: AnyObject> (type: T.Type) -> T {

    type as AnyClass === Raw.self as AnyClass { }

    // return something
}

This solution seems to work with pure Swift classes too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM