Swift类扩展了Objective C委托

时间:2015-11-30 00:31:29

标签: objective-c swift

我正在尝试在Swift类中扩展Objective C类。这是我到目前为止的地方:

SINMessageClientDelegate是Objective C类。 ViewController是用Swift编写的。我已经有了Bridging Header,所以我可以在我的Swift类中使用Objective C对象。

这是我的Swift代码类定义的样子:

class ViewController: UIViewController, SINMessageClientDelegate {

我收到以下错误:

Type "ViewController does not conform to protocol SINMessageClientDelegate"

这就是SINMessageClientDelegate的定义:

@protocol SINMessageClientDelegate <NSObject>

- (void)messageClient:(id<SINMessageClient>)messageClient didReceiveIncomingMessage:(id<SINMessage>)message;

- (void)messageSent:(id<SINMessage>)message recipientId:(NSString *)recipientId;

- (void)messageDelivered:(id<SINMessageDeliveryInfo>)info;

- (void)messageFailed:(id<SINMessage>)message info:(id<SINMessageFailureInfo>)messageFailureInfo;

我尝试在ViewController中使用Swift创建这些方法:

// Tells the delegate that a message has been received.
func messageClient(id: SINMessageClient, didReceiveIncomingMessage:SINMessage)
{

}

// Tells the delegate that a message for a specific recipient has been sent by the local user.
func messageSent(id: SINMessage, recipientId: NSString)
{

}

// Tells the delegate that a message has been delivered (to a particular recipient).

func messageDelivered(id: SINMessageDeliveryInfo)
{

}

func messageFailed(id: SINMessage, info: SINMessageFailureInfo)
{

}

有人可以建议这样做的正确方法,因为我在添加代码后遇到同样的错误吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

你提出问题的方式中的一个问题是你使用了错误的词语。你不是“扩展课程”。您符合(或采用协议

然而,麻烦的是你采用它(符合它),正如错误信息正确告诉你的那样。原因显然是你不知道如何阅读Objective-C。你需要学会这样做才能继续。例如,给定此Objective-C声明:

- (void)messageClient:(id<SINMessageClient>)messageClient 
    didReceiveIncomingMessage:(id<SINMessage>)message;

Swift实现需要:

func messageClient(SINMessageClient, 
    didReceiveIncomingMessage message: SINMessage) { /* ... */ }

而你拥有的东西并不是完全相同的东西。你有这个:

func messageClient(id: SINMessageClient, 
    didReceiveIncomingMessage:SINMessage) { /* ... */ }

这不是匹配,所以你没有实现所需的方法,而是一些完全不同的方法。这是合法的,但它与你应该遵守的协议无关。其余的声明也一样。