简体   繁体   中英

Swift class add “@objc” for why

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?

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

@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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM