我想尝试一下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 ... } }
KPM.. 461
正确的Swift运算符是is
:
if touch.view is UIPickerView { // touch.view is of type UIPickerView }
当然,如果你还需要将视图分配给一个新的常量,那么if let ... as? ...
语法就是你的男孩,正如凯文提到的那样.但是如果您不需要该值并且只需要检查类型,那么您应该使用is
运算符.
正确的Swift运算符是is
:
if touch.view is UIPickerView { // touch.view is of type UIPickerView }
当然,如果你还需要将视图分配给一个新的常量,那么if let ... as? ...
语法就是你的男孩,正如凯文提到的那样.但是如果您不需要该值并且只需要检查类型,那么您应该使用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) { } }
编辑
正如@ Kevin的回答所指出的那样,正确的方法是使用可选的类型转换运算符as?
.您可以在section Optional Chaining
子节中阅读更多相关信息Downcasting
.
编辑2
正如用户@KPM的另一个答案所指出的那样,使用is
运算符是正确的方法.
您可以将检查和强制转换合并为一个语句:
let touch = object.anyObject() as UITouch if let picker = touch.view as? UIPickerView { ... }
然后你可以picker
在if
块内使用.