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
, not Array
. 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
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(f: (T -> U?)) -> Array {
var result = Array()
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 }