Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @objc before class and @objc(class_name) above class in swift?

Tags:

class

swift

What's the difference between :

@objc class MyClass: NSObject{}

and

@objc(MyClass)
class MyClass: NSObject{}
like image 945
pyanfield Avatar asked Nov 04 '15 02:11

pyanfield


People also ask

What does @objc do in Swift?

@objc means you want your Swift code (class, method, property, etc.) to be visible from Objective-C. dynamic means you want to use Objective-C dynamic dispatch.

What is@ objc class?

@objc(xxx) , however, is used to define an alternative name for the class (to be used by the runtime and from Objective-C code). This modifier is only useful if you want a different name to use in your runtime / Objective C code.

Do Swift classes inherit from NSObject?

You don't have to inherit from NSObject in Swift, but you did in Objective-C and in fact there are some behaviors you can only have if you do inherit from it. More on that in project 12, but for now just make sure you inherit from NSObject .


1 Answers

The @objc modifier is being deprecated in Swift 2. All classes that were marked as @objc have to be a subclass of NSObject, thus making the modifier @objc redundant.

@objc(xxx), however, is used to define an alternative name for the class (to be used by the runtime and from Objective-C code).

This modifier is only useful if you want a different name to use in your runtime / Objective C code.

By default the runtime name is same as the declared name, prefixed by the module name and a dot. For example, class X: NSObject {} would be @objc(MyModule.X) at runtime.

like image 170
Vatsal Manot Avatar answered Oct 11 '22 12:10

Vatsal Manot