I want to check if the elements of an Array are a subclass of UILabel in Swift:
import UIKit
var u1 = UILabel()
u1.text=\"hello\"
var u2 = UIView(frame: CGR
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 }
You may compare classes using the following in swift:
return object.dynamicType == otherObject.dynamicType
dynamicType will return an instance of Class which you may compare
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.
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 AnyClass
let 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 Array
MyProject.Customer_Customer_ //for a CoreData class named Customer