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 }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…