在Swift中使用isKindOfClass
我试图拿起一些Swift lang,我想知道如何将下面的Objective-C转换成Swift:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; UITouch *touch = [touches anyObject]; if ([touch.view isKindOfClass: UIPickerView.class]) { //your touch was in a uipickerview ... do whatever you have to do } }
更具体地说,我需要知道如何在新语法中使用isKindOfClass
。
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { ??? if ??? { // your touch was in a uipickerview ... } }
正确的Swift运算符is
:
if touch.view is UIPickerView { // touch.view is of type UIPickerView }
当然,如果你还需要将视图分配给一个新的常量,那么if let ... as? ...
语法是你的男孩,正如凯文提到的那样。 但是,如果你不需要这个值,只需要检查types,那么你应该使用is
操作符。
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) let touch : UITouch = touches.anyObject() as UITouch if touch.view.isKindOfClass(UIPickerView) { } }
编辑
正如@凯文的答案所指出的 ,正确的方法是使用可选的types转换操作符as?
。 您可以在“ Optional Chaining
子节Downcasting
部分阅读更多信息。
编辑2
正如用户@KPM指出的另一个答案 ,使用is
运算符是正确的方法。
您可以将支票和演员组合成一个声明:
let touch = object.anyObject() as UITouch if let picker = touch.view as? UIPickerView { ... }
然后你可以在if
块中使用picker
。
我会用:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) let touch : UITouch = touches.anyObject() as UITouch if let touchView = touch.view as? UIPickerView { } }
使用新的Swift 2语法的另一种方法是使用guard并将其全部嵌套在一个条件中。
guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else { return //Do Nothing } //Do something with picker