我想检查数组的元素是否是Swift中UILabel的子类:
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运算符测试值的类型:
is
var onlyUILabels = myArray.filter { $0 is UILabel }
顺便说一句,这仍然会产生Array<UIView>,而不是Array<UILabel>。从Swift 2 beta系列开始,您可以为此使用flatMap:
Array<UIView>
Array<UILabel>
var onlyUILabels = myArray.flatMap { $0 as? UILabel }
以前(Swift 1),您可以投射,虽然可以,但是感觉有点难看。
var onlyUILabels = myArray.filter { $0 is UILabel } as! Array<UILabel>
否则,您需要某种方式来构建仅包含标签的列表。不过,我看不到任何标准。也许像这样:
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 }