Skip to main content

Can you explain what the @objc keyword does?

· 2 min read
Ace the iOS Interview
Aryaman Sharda
Sources & Resources
TL/DR

The @objc keyword makes Swift code accessible to Objective-C.

If you’re applying to an older company, they’ll likely have a substantial part of their codebase still in Objective-C. So, you’ll need to be comfortable with using both Objective-C and Swift in the same project.

This attribute is used to make your Swift code accessible to the Objective-C runtime.

Anytime you have a Swift class, property, or protocol that you want to access in Objective-C code, you’ll need to prefix it with this keyword.

// The ViewController is accessible in an Objective-C environment
@objc class ViewController: UIViewController {

// Visible in Objective-C
@objc var username: String!

// Not visible in Objective-C
private var password: String!

override func viewDidLoad() {
super.viewDidLoad()
}
}

@objc, when added to a class declaration, only exposes the public init. You will have to add it manually to all other properties and methods you want to expose.

If you want to expose all public properties and methods to Objective-C, you can use @objcMembers instead.

In Bullets
  • Purpose:

    • The @objc keyword is used to expose Swift code to the Objective-C runtime.
  • Usage:

    • Classes: Annotate Swift classes with @objc to make them accessible from Objective-C.
      @objc class MyClass: NSObject {
      // This class can be accessed from Objective-C code
      }
    • Methods: Use @objc for methods you want to be callable from Objective-C.
      @objc func myMethod() {
      // This method can be called from Objective-C
      }
    • Properties: Apply @objc to properties that need to be accessed in Objective-C.
      @objc var myProperty: String?
  • Limitations:

    • Private Members: Properties and methods marked private are not exposed to Objective-C even if they are annotated with @objc.
      @objc private var secret: String // Not visible in Objective-C
  • Objective-C Compatibility:

    • Enables interoperability between Swift and Objective-C, essential for projects with mixed-language codebases.