How to test for the class of a variable in Swift? How to test for the class of a variable in Swift? ios ios

How to test for the class of a variable in Swift?


Swift has the is operator to test the type of a value:

var onlyUILabels = myArray.filter { $0 is UILabel }

As a side note, this will still produce an Array<UIView>, not Array<UILabel>. As of the Swift 2 beta series, you can use flatMap for this:

var onlyUILabels = myArray.flatMap { $0 as? UILabel }

Previously (Swift 1), you could cast, which works but feels a bit ugly.

var onlyUILabels = myArray.filter { $0 is UILabel } as! Array<UILabel>

Or else you need some way to build a list of just the labels. I don't see anything standard, though. Maybe something like:

extension Array {    func mapOptional<U>(f: (T -> U?)) -> Array<U> {        var result = Array<U>()        for original in self {            let transformed: U? = f(original)            if let transformed = transformed {                result.append(transformed)            }        }        return result    }}var onlyUILabels = myArray.mapOptional { $0 as? UILabel }


In Swift you should do the is keyword if you are wondering about the according class. In the filter-closure you can use $0 to specify the first parameter.

Sample

var (a,b,c,d) = ("String", 42, 10.0, "secondString")let myArray: Array<Any> = [a,b,c,d]var onlyStrings = myArray.filter({ return $0 is String })onlyStrings // ["String", "secondString"]


Without getting to the object.class( ) nirvana, in Swift, we can still use the Objective-C Runtime to get some useful information about the object´s class as follows (and not exactly bridging to Objective-C):

let objectClass: AnyClass = object_getClass(object) as AnyClasslet objectClassName =  NSStringFromClass(objectClass)println("Class = \(objectClassName)")

Note that we get the "MyProject." or (sometimes) the "Swift." prefix, depending if you refer to your own classes or Swift classes:

UILabel // UILabel    Swift._NSSwiftArrayImpl //Swift ArrayMyProject.Customer_Customer_   //for a CoreData class named Customer