I am having trouble making a swift class conform to an objective c protocol. It is easy to implement the methods in an objective c protocol in swift, but I can't implement the properties in the following protocol.
The protocol is
@protocol ATLParticipant <NSObject>
@property (nonatomic, readonly) NSString *firstName;
@property (nonatomic, readonly) NSString *lastName;
@property (nonatomic, readonly) NSString *fullName;
@property (nonatomic, readonly) NSString *participantIdentifier;
@end
I have made this swift class which should conform to it, but Xcode says it doesn't.
class ConversationParticipant: NSObject, ATLParticipant {
var firstName: NSString?
var lastName: NSString?
var fullName: NSString?
var participantIdentifier: NSString?
override init() {
super.init()
}
}
I have tried making the member variables optional (as above), and unwrapped, and prefixed with private(set) to make them readonly, but none of these variations work.
Objective-C uses angle brackets to indicate conformance to a protocol. This example declares a weak property for a generic object pointer that conforms to the XYZPieChartViewDataSource protocol.
In order to use Swift code inside Objective-C one must scrifice some Swift features and write a wrapper around original Swift code that won't use non-compatible features (like structs, generics, enum associated values, protocol extensions etc.). All wrapper classes must inherit NSObject .
You can have properties in a protocol, provided every class that conforms to your protocol have a corresponding @synthesize for that property, or provide a getter and setter. But with a class category you generally can't add instance variables to a class.
In Objective-C, protocols are declared with the “@protocol” keyword. Below is an example of declaring a protocol containing one required method. In Swift, the syntax is a little different but the idea is the same. In Objective-C, you add the protocol name in angle brackets beside the class interface declaration.
Found the solution, in Swift you shouldn't use NSString, but the String type.
class ConversationParticipant: NSObject, ATLParticipant {
var firstName: String!
var lastName: String!
var fullName: String!
var participantIdentifier: String!
var avatarImage: UIImage!
override init() {
super.init()
}
}
I implemented this solution and still got an error:
"Type 'ConversationParticipant' does not conform to protocol 'ATLAvatarItem'"
I added the following to solve it:
var avatarImageURL: NSURL!
var avatarImage: UIImage!
var avatarInitials: String!
and worked just fine.
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