Should I avoid using @objc?

I was curious about whether I should avoid using @objc in my swift methods. What benefits would that provide?

According to Xcode swift3 -> swift4 migrator, not using @objc everywhere will result in a reduced binary size

https://help.apple.com/xcode/mac/current/#/deve838b19a1

What cukr said, but also:

  • @objc is only supported on Apple platforms. If you’re writing general code that might end up running on other platforms some day, you’ll want to avoid it.

  • @objc prevents you from using many of Swift’s nicer features. Like enums with associated values:

      enum State {
          case initialised
          case open(Connection)
          case closed
      }
    
      @objc func stop(state: State)
                 ^ Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C
    

    And generics:

      @objc func sum<C>(collection: C) where C: Collection, C.Element == Int
                 ^ Method cannot be marked @objc because it has generic parameters
    

    .

IMO you should only use @objc if you absolutely need it for interacting with Apple frameworks, tools, and techniques.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

2 Likes