将isKindOfClass与Swift一起使用

时间:2014-06-03 15:59:19

标签: ios 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 ...

    }
}

5 个答案:

答案 0 :(得分:449)

正确的Swift运算符是is

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

当然,如果你还需要将视图分配给一个新常量,那么if let ... as? ...语法就是你的男孩,正如凯文所说。但是,如果您不需要该值并且只需要检查类型,那么您应该使用is运算符。

答案 1 :(得分:131)

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's answer所指出的,正确的方法是使用可选的类型转换运算符as?。您可以在Optional Chaining子部分Downcasting部分了解更多相关信息。

修改2

正如other answer by user @KPM所指出的那样,使用is运算符是正确的方法。

答案 2 :(得分:48)

您可以将检查和强制转换合并为一个语句:

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

然后,您可以在picker块中使用if

答案 3 :(得分:1)

我会用:

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
    {

    }
}

答案 4 :(得分:-3)

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

select