Sobes.tech
Middle

What happens if a class is marked as Objective-C?

sobes.tech AI

Answer from AI

A class marked with the @objc attribute becomes accessible from Objective-C code. This ensures interoperability between Swift and Objective-C.

Key aspects:

  1. Accessibility from Objective-C: Methods, properties, and initializers of this class can be called from Objective-C.
  2. Dynamic dispatch: @objc often implies dynamic dispatch, meaning method calls are determined at runtime rather than compile time. This is necessary for some Objective-C features like Key-Value Observing (KVO), Objective-C Runtime, and @dynamic.
  3. Inheritance from NSObject: To be fully accessible from Objective-C, a class usually needs to inherit from NSObject. Classes not inheriting from NSObject can also be marked @objc, but their functionality in Objective-C may be limited.
  4. Selectors: Methods of @objc classes can be used with selectors (#selector), which is critical for Target-Action pattern, NSTimer, and NotificationCenter in Objective-C style.
  5. Renaming: When exported to Objective-C, Swift class, method, and property names can be changed. The @objc attribute allows explicitly specifying the Objective-C name using @objc(<ObjCName>).

Example:

import Foundation

@objc(MySwiftClass) // Explicitly name it MySwiftClass in Objective-C
class MyClass: NSObject {
    @objc var myProperty: Int = 0 // Accessible from Objective-C

    @objc func myMethod(value: Int) { // Accessible from Objective-C
        print("Value: \(value)")
    }

    // Not accessible as a method from Objective-C by default
    func swiftOnlyMethod() {
        print("Swift only")
    }
}

As a result, this Swift class will be visible in Objective-C as MySwiftClass with accessible properties myProperty and method myMethodWithIntValue:.

What happens if a class is marked as Objective-C? — iOS - sobes.tech