委托Swift的Objective-C协议 [英] Delegating Objective-C Protocol on Swift
问题描述
为此,我正在中继 CocoaAsyncSocket 项目。
我成功地使用Bridging-Header.h导入CocoaAsyncSocket库我可以从Objective-C类调用函数,但是我无法在swift上写代理函数。
这是我设置的代码Socket并将ViewController.swif定义为监听器的委托类:
func setupSocket(){
var udpSocket :GCDAsyncUdpSocket = GCDAsyncUdpSocket(delegate:self,delegateQueue:dispatch_get_main_queue())
var error:NSError?
let port:UInt16 = 12121
let address:String =228.5.12.12
udpSocket.bindToPort(port,error:& error)
udpSocket.joinMulticastGroup(address,错误:& error)
udpSocket.enableBroadcast(true,error:& error)
println(228.5.12.12)
}
这是Objective-C中的前委托函数:
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext;
最后,这是我如何在Swift上实现这个功能:
覆盖func udpSocket(sock:GCDAsyncUdpSocket !, didReceiveData data:NSData !, fromAddress address:NSData !, withFilterContext filterContext:AnyObject!){
println(data)
}
声明ViewController类来实现正确的协议: p>
class ViewController:UIViewController,GCDAsyncUdpSocketDelegate {
...
}
除了覆盖之外,我没有编译错误。
问题:
覆盖
关键字用于覆盖超类的方法。由于您不会覆盖任何方法,因此不需要覆盖
关键字。
I'm implementing an UDP Listener on iOS using the Swift language.
For this I'm relaying on the CocoaAsyncSocket project.
I was succeeded on importing the CocoaAsyncSocket library using a Bridging-Header.h, I could call the functions from the Objective-C classes, but I'm not able to write the delegate function on swift.
This is the code where I set the Socket and define the ViewController.swif as the delegate class for the listener:
func setupSocket() {
var udpSocket : GCDAsyncUdpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
var error : NSError?
let port : UInt16 = 12121
let address : String = "228.5.12.12"
udpSocket.bindToPort(port, error: &error)
udpSocket.joinMulticastGroup(address, error: &error)
udpSocket.enableBroadcast(true, error: &error)
println("228.5.12.12")
}
This is the former delegate function in Objective-C:
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext;
And finally, this is how I'm implementing the function on Swift:
override func udpSocket(sock : GCDAsyncUdpSocket!, didReceiveData data : NSData!, fromAddress address : NSData!, withFilterContext filterContext : AnyObject!) {
println(data)
}
ViewController class is declared to implement the right protocol:
class ViewController: UIViewController, GCDAsyncUdpSocketDelegate {
...
}
I got no compile error except for the override.
Question: What am I doing wrong?
override
keyword is for overriding methods of superclass. As you are not overriding any methods, override
keyword is not needed.
这篇关于委托Swift的Objective-C协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!