I've put the following into a Playground to try and understand this and I just don't:
import Foundation
@objc protocol Sample {
var value: Int { get set }
func increase()
func decrese()
}
extension Sample {
func increase() {
value += 1
}
func decrease() {
value -= 1
}
}
class Test: Sample {
var value: Int = 0
}
The error appears next to the class
declaration for Test
saying:
Non-'@objc' method 'increase()' does not satisfy requirement of '@objc' protocol 'Sample'
If I re-declare increase()
and decrease()
in the class then the warning is silenced. Or also if I remove the declarations from the protocol. Could someone please explain?
EDIT
I do need an Objective-C class to conform to this protocol as well, hence the @objc
at the start.
The problem is that you're defining these methods in a protocol extension. This is used to define a “default implementation” for a protocol (ie if a type doesn't implement the method, the protocol's implementation will be called).
But Objective-C doesn't have the concept of default implementations for protocols. So it doesn't makes sense to declare the protocol as @objc
and have default implementations within the Swift protocol extension. An Objective-C class conforming to this protocol would never be able to enjoy these Swift default implementations.
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.