2
votes

Here's a link to a Swift tutorial.

I read the protocol section,i know if protocol is marked with the @objc:

@objc protocol CounterDataSource {
    optional func incrementForCount(count: Int) -> Int
    optional var fixedIncrement: Int { get }
}

this mean this protocol in order to specify optional requirements and can be adopted only by classes

but tutorial didn't say why the class need to marked with the @objc too??

@objc class Counter {
    var count = 0
    var dataSource: CounterDataSource?
    func increment() {
      if let amount = dataSource?.incrementForCount?(count) {
        count += amount
      } else if let amount = dataSource?.fixedIncrement? {
        count += amount
      }
    }
}

if i remove @objc from class , compiler didn't show error message too

so what different between add @objc to class or not?

2

2 Answers

6
votes

Deprecation

It is no longer possible in latest Swift releases to use @objc w/o NSObject so this answer is deprecated.

Original

@objc is prefixed to classes to allow them to be used in ObjC. If you're dealing purely in Swift, it is unnecessary.

Also, if your class inherits from an ObjC class, the prefix is unnecessary.

0
votes

For example #selector is owned by Obj-c,

In swift, we'll use #selector in .addTarget or in .target of an object. There we should prefix @objc for targeting method.

Example:

@objc func dummy(_ sender: UIButton) {
    print("xxx")
}

above method will be using in a UIButton's target like

dummyButton.addTarget(self, action: #selector(self. dummy(_:)), for: .touchUpInside)

this is why we are using @objc as prefix in swift.