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:
- Accessibility from Objective-C: Methods, properties, and initializers of this class can be called from Objective-C.
- Dynamic dispatch:
@objcoften 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. - Inheritance from
NSObject: To be fully accessible from Objective-C, a class usually needs to inherit fromNSObject. Classes not inheriting fromNSObjectcan also be marked@objc, but their functionality in Objective-C may be limited. - Selectors: Methods of
@objcclasses can be used with selectors (#selector), which is critical for Target-Action pattern, NSTimer, and NotificationCenter in Objective-C style. - Renaming: When exported to Objective-C, Swift class, method, and property names can be changed. The
@objcattribute 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:.