一尘不染

在Swift中使用isKindOfClass

swift

我正在尝试学习一些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 ...

    }
}

阅读 2767

收藏
2020-07-07

共1个答案

一尘不染

正确的Swift运算符是is

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

当然,如果您还需要将视图分配给新的常量,那么if let ... as? ...语法就是您的孩子,就像Kevin提到的那样。但是,如果您不需要该值而只需要检查类型,则应使用is运算符。

2020-07-07