将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 ...
    }
}

合适的Swift运算符是is:

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

当然,如果您还需要将视图分配给一个新的常量,那么if let ... as? ...语法就是您的孩子,正如Kevin提到的那样。但是,如果您不需要值,只需要检查类型,那么您应该使用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?。您可以在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

相关内容

  • 没有找到相关文章

最新更新