Mobile Development Swift Subjective
Oct 04, 2025

What is the purpose of the @objc attribute in Swift?

Detailed Explanation
The @objc attribute exposes Swift code to the Objective-C runtime, enabling interoperability.\n\n• **Basic Usage:**\n\nclass MyClass: NSObject {\n @ func handleTap() {\n print("Button tapped")\n }\n \n @ var title: String = "Default"\n \n @objc func classMethod() {\n print("Class method called")\n }\n}\n\n\n• **Automatic @objc Inference:**\n• NSObject subclasses\n• Protocol requirements marked @objc\n• Overrides of @objc methods\n• Target-action patterns\n\n\n// Automatic @objc for UIButton target\nbutton.addTarget(self, action: #selector(handleTap), for: .touchUpInside)\n\n\n• **@objc vs @objcMembers:**\n\n@objcMembers\nclass AutoExposedClass: NSObject {\n func method1() {} // Automatically @objc\n func method2() {} // Automatically @objc\n \n @ func swiftOnlyMethod() {} // Opt out\n}\n\n\n• **Limitations:**\n• Performance overhead\n• Limited to Objective-C compatible types\n• Dynamic dispatch\n• Larger binary size\n\n• **Use Cases:**\n• UIKit target-action\n• KVO (Key-Value Observing)\n• Objective-C interop\n• Runtime introspection
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback