将isKindOfClass与Swift一起使用

lke*_*hll 225 reflection introspection 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
    }
}
Run Code Online (Sandbox Code Playgroud)

更具体地说,我需要知道如何isKindOfClass在新语法中使用.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    ???

    if ??? {
        // your touch was in a uipickerview ...

    }
}
Run Code Online (Sandbox Code Playgroud)

KPM*_*KPM 461

正确的Swift运算符是is:

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,这很有效.干净整洁. (2认同)
  • 也适用于Swift 3! (2认同)

Rui*_*res 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)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

正如@ Kevin的回答所指出的那样,正确的方法是使用可选的类型转换运算符as?.您可以在section Optional Chaining子节中阅读更多相关信息Downcasting.

编辑2

正如用户@KPM另一个答案所指出的那样,使用is运算符是正确的方法.

  • 通过将答案放在你的手中来窃取其他用户的代表是很糟糕的. (4认同)

Kev*_*vin 48

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

let touch = object.anyObject() as UITouch
if let picker = touch.view as? UIPickerView {
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后你可以pickerif块内使用.

  • 这是"更正确"的答案,因为它使用Swift'作为?' 运营商.该文档指出"在Objective-C中,您使用isKindOfClass:方法来检查对象是否属于某种类型类型,并使用conformsToProtocol:方法来检查对象是否符合指定的协议.在Swift中,您完成此操作任务通过使用is运算符来检查类型,或使用as?运算符向下转换为该类型." [Apple文档](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html) (3认同)