What is the @objc attribute and when to use @objc in swift code?

What is the @objc attribute and when to use @objc in swift code?

The @objc attribute makes your Swift API available in Objective-C and the Objective-C runtime.

A Swift class or protocol must be marked with the @objc attribute to be accessible and usable in Objective-C. This attribute tells the compiler that this piece of Swift code can be accessed from Objective-C. If your Swift class is a descendant of an Objective-C class, the compiler automatically adds the @objc attribute for you.

By default Swift generates code that is only available to other Swift code, but if you need to interact with the Objective-C runtime – all of UIKit, for example – you need to tell Swift what to do.

Also Read : how to detect low power mode in swift

Don’t worry: if you forget to add @objc when it’s needed, your code simply won’t compile – it’s not something you can forget by accident and introduce a bug.

To use Swift’s functions from Objective-C:

Swift’s class should be extended from NSObject

Mark Swift’s:

a. @objcMembers class – to expose all public fields and methods

b. @objc class – to expose public init().
@objc public fields and methods – to expose them selectively

Swift’s method will be available by the next naming:

With::
For example: public func printHelloWorld(arg1: String, arg2:String) is reached through: [someObject printHelloWorldWithArg1: arg2:];

To expose a method to Objective-C, just write @objc before its name like this:

class MyController: UIViewController {
@objc func authenticateUser() {

}
}

That whole class is automatically Objective-C friendly because it inherits from UIViewController, but if you need it you can also explicitly make a class open to Objective-C by marking it @objc.

 

class ExampleClass: NSObject {
@objc var enabled: Bool {
@objc(isEnabled) get {
// Return the appropriate value
}
}
}

 

@objc private dynamic var originalProperty: String

@objc private static let keyPathsForValuesAffectingDependentProperty: Set = [
#keyPath(originalProperty)
]
@objc public var dependentProperty: String { return changeItSomehow(self.originalProperty) }

Discover more from CODE t!ps

Subscribe to get the latest posts sent to your email.

Scroll to Top

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading