我试图拿起一点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 ...

    }
}

当前回答

我会用:

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操作符是:

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

当然,如果你还需要将视图赋值给一个新的常量,那么if let…是吗?... 正如凯文所说,语法是你的孩子。但如果不需要值,只需要检查类型,则应该使用is操作符。

我会用:

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
    {

    }
}
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)
    {

    }
}

Edit

正如@Kevin的回答中指出的那样,正确的方法是使用可选的类型转换操作符作为?你可以阅读更多关于它的章节可选链子章节下casting。

编辑2

正如用户@KPM在另一个回答中指出的那样,使用is操作符是正确的方法。

使用新的Swift 2语法的另一种方法是使用guard并将其嵌套在一个条件中。

guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
    return //Do Nothing
}
//Do something with picker

你可以将检查和强制转换组合成一个语句:

let touch = object.anyObject() as UITouch
if let picker = touch.view as? UIPickerView {
    ...
}

然后你可以在if块中使用picker。