Home What is @objcMembers and @objc in Swift
Post
Cancel

What is @objcMembers and @objc in Swift

If you tried to use Swift code in Objective-C and you were not able to create an object from a class or to call a swift method, that’s most probably because you didn’t add the @objc to the class or the method.

By default, Swift code is available for Swift code but not for Objective-C. To make the code available for Objective-C you can use one of two things:

objc

If you want to make one method or property available to Objective-C, you can use the @objc attribute.

1
2
3
4
  @objc
  func doSomething() {
    print("hello!")
  }

In Objective-C you can call it like this.

  [someClass doSomething];

@objcMembers

If you want all the methods and properties to be available for Objective-C, you can use the @objcMembers attribute.

1
2
3
4
5
6
@objcMembers
class SomeClass {
  func doSomething() {
    print("hello!")
  }
}

In that way, it will be available to the objective-c code without adding @objc specifically to the methods.

  [someClass doSomething];

-❤️~.
If you have any questions you can send me a message on Twitter or facebook. Also you can check my Github page or my Apps.

This post is licensed under CC BY 4.0 by the author.