使用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 ...


}
}
134703 次浏览
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 ChainingDowncasting子节中阅读更多关于它的内容。

编辑2

正如其他由用户@KPM回答中指出的那样,使用is操作符是正确的方法。

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

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

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

正确的Swift操作符是is:

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

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

我会用:

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
{


}
}