Fix: Type Checking with isKindOfClass in Swift Using the is Operator

Fix: Type Checking with isKindOfClass in Swift Using the is Operator

Written by

in

Quick answer: In Swift, replace Objective-C’s isKindOfClass: with the is operator for type checks (e.g., if view is UIPickerView) and use as? for conditional downcasting when you need the typed instance. The is operator is cleaner, safer, and the idiomatic Swift approach.

Why this happens

Developers migrating from Objective-C often reach for isKindOfClass: because it’s the familiar way to check an object’s type at runtime. In Objective-C, isKindOfClass: returns a BOOL indicating whether the receiver is an instance of a given class or any subclass. Swift provides this method on NSObject subclasses for interoperability, but it’s not the native Swift way to perform type checks.

Swift’s type system is designed around value types, protocols, and generics. The language encourages compile-time safety over runtime introspection. When you write view.isKindOfClass(UIPickerView.self) in Swift, it compiles because UIView inherits from NSObject, but you’re bypassing Swift’s stronger type checking and pattern matching capabilities. The is operator and as? conditional cast are the idiomatic replacements that integrate with Swift’s control flow and optional handling.

How to fix it

1. Use the is operator for simple type checks

The most direct replacement for isKindOfClass: is the is operator. It returns a Bool and reads like English:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    guard let touch = touches.first else { return }

    if touch.view is UIPickerView {
        // touch.view is a UIPickerView or subclass
        print("Touch occurred in a picker view")
    }
}

The is operator works with any type—classes, structs, enums, and protocols. It checks the dynamic type of the instance at runtime, including inheritance hierarchies. This is the preferred approach when you only need to know whether the instance matches a type, not to use it as that type.

2. Use as? for conditional downcasting when you need the typed value

If you need to access properties or methods specific to the subclass after the check, combine the check and cast in one step with optional binding:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    guard let touch = touches.first,
          let pickerView = touch.view as? UIPickerView else { return }

    // pickerView is now typed as UIPickerView
    let selectedRow = pickerView.selectedRow(inComponent: 0)
    print("Selected row: \(selectedRow)")
}

This pattern—if let x = y as? Type—is the Swift equivalent of Objective-C’s:

if ([view isKindOfClass:[UIPickerView class]]) {
    UIPickerView *picker = (UIPickerView *)view;
    // use picker
}

But it’s safer: the cast either succeeds and gives you a non-optional typed value, or fails and the block doesn’t execute. There’s no force-unwrap risk.

3. Use as! only when the cast is guaranteed to succeed

Force casting with as! crashes if the instance isn’t the expected type. Reserve it for cases where the type is statically known, such as when unwrapping a view from a storyboard with a known identifier:

// Only when you're certain—e.g., a prototype cell registered with a specific class
let cell = tableView.dequeueReusableCell(withIdentifier: "PickerCell", for: indexPath) as! PickerCell

In the touchesBegan example, as! would be wrong because touch.view could be any UIView subclass.

4. Prefer protocol conformance checks over concrete class checks

Swift encourages programming to protocols. If multiple view types share behavior, define a protocol and check for that:

protocol SelectableView: UIView {
    var selectedIndex: Int { get set }
}

// Later...
if let selectable = touch.view as? SelectableView {
    selectable.selectedIndex = 5
}

This works across unrelated class hierarchies and with value types, making your code more flexible than class-based checks.

How to prevent it

  • Default to is for boolean type checks — it’s readable, fast, and doesn’t create optionals.
  • Use as? with if let/guard let when you need the typed instance — combines check and cast safely.
  • Avoid isKindOfClass in new Swift code — it signals Objective-C thinking and doesn’t work with Swift-only types (structs, enums, non-NSObject classes).
  • Model shared behavior with protocols — check for protocol conformance instead of concrete subclasses when possible.
  • Enable strict concurrency checking — the compiler will warn about unsafe casts in @Sendable contexts.

FAQ

Can I still use isKindOfClass in Swift?

Yes, isKindOfClass(_:) is available on any NSObject subclass (including UIView, UIViewController, etc.) for Objective-C interoperability. However, it only works with Objective-C classes, not Swift structs, enums, or classes that don’t inherit from NSObject. The is operator works universally.

What’s the difference between is and as? performance-wise?

Both perform a runtime type check. is returns a Bool; as? returns an optional of the target type. When you need the typed value, as? with optional binding is a single check. Using is followed by a separate as! or as? does the check twice, so prefer the combined form.

Does is work with protocols?

Yes. instance is SomeProtocol checks whether the instance conforms to the protocol at runtime. This works for @objc protocols and, in Swift 5.7+, for non-@objc protocols with any existential types. It’s the primary way to test protocol conformance dynamically.\n

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.