如何在Swift中测试变量的类? [英] How to test for the class of a variable in Swift?
本文介绍了如何在Swift中测试变量的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查数组的元素是否是Swift中UILabel的子类:
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: CGRectMake(0, 0, 200, 20))
var u3 = UITableView(frame: CGRectMake(0, 20, 200, 80))
var myArray = [u1, u2, u3]
var onlyUILabels = myArray.filter({"what to put here?"})
不与目标c搭桥.
推荐答案
Swift具有is
运算符来测试值的类型:
Swift has the is
operator to test the type of a value:
var onlyUILabels = myArray.filter { $0 is UILabel }
作为旁注,这仍将生成Array<UIView>
,而不是Array<UILabel>
.从Swift 2 beta系列开始,您可以为此使用flatMap:
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 }
以前(快速1),您可以投射,虽然可以,但是感觉有点难看.
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 }
这篇关于如何在Swift中测试变量的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文