I'm working on converting my project from Objective-c to Swift, and a Swift class I'm using, I have a protocol
I'm trying to access in an Objective-c class. My problem is, the delegate
is not accessible in the objective-c class. Here is my swift class:
protocol RateButtonDelegate {
func rateButtonPressed(rating: Int)
}
class RateButtonView: UIView {
var delegate: RateButtonDelegate?
var divider1: UIView!
var divider2: UIView!
}
When I look at the MyProject-Swift.h
file, I don't see the delegate
:
@interface RateButtonViewTest : UIView
@property (nonatomic) UIView * divider1;
@property (nonatomic) UIView * divider2;
@end
and when I try to use rateButtonView.delegate
in my Objective-c class, I get a compiler error.
Anyone know the issue? How do access a Swift protocol in Objective-c?
You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file. This file is an Objective-C header that declares the Swift interfaces in your target, and you can think of it as an umbrella header for your Swift code.
Objective-C Language Protocols Conforming to Protocols It is also possible for a class to conform to multiple protocols, by separating them with comma. Like when conforming to a single protocol, the class must implement each required method of each protocols, and each optional method you choose to implement.
In Swift, calling a method will be decided at compile time and is similar to object-oriented programming, whereas in Objective C, calling a method will be decided at runtime, and also Objective C has special features like adding or replacing methods like on a class which already exists.
You need to mark your protocol with the @objc
attribute for it to be accessible from Objective-C:
@objc protocol RateButtonDelegate {
func rateButtonPressed(rating: Int)
}
This page from Apple's documentation covers the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With