Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Swift protocol in Objective-C

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?

like image 758
coder Avatar asked Oct 20 '14 17:10

coder


People also ask

Can Swift protocol be used 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.

How do you conform to a protocol in Objective-C?

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.

What is difference between Objective-C protocol and Swift protocol?

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.


1 Answers

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.

like image 122
Nate Cook Avatar answered Sep 30 '22 13:09

Nate Cook