ios - 在 Swift 中使用 isKindOfClass

标签 ios swift reflection introspection

我正在尝试学习一些 Swift 语言,我想知道如何将以下 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 运算符是:

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

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

关于ios - 在 Swift 中使用 isKindOfClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24019707/

相关文章:

c++ - C++中的“Poor Man'反射”(又名自下而上的反射)

ios - 将 max float 用于 boundingRectWithSize 的高度是否有效

iOS UIPageViewController 脊柱位置

ios - 解析登录和注册功能 SWIFT

c# - 使用 System.Type 中的泛型类型调用泛型方法

c# - 反射.Assembly::Load 方法

ios - iOS上的正则表达式错误

android - 在代号一中使用 .NET Web 服务

ios - insertRowAtIndexes watchKit Swift

ios - addAuthStateDidChangeListener 被调用两次的问题