Swift - 为singleton设置委托 [英] Swift - set delegate for singleton
本文介绍了Swift - 为singleton设置委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的事情:
class SocketManager {
static let instance: SocketManager
var socket = Socket()
}
extension SocketManager: SocketDelegate {
func someFunc() {
}
}
Socket
是一个拥有协议的类
和委托
protocol SocketDelegate: class {
func someFunc()
}
class Socket {
weak var delegate: SocketDelegate?
}
如何设置 socket.delegate
到 SocketManager.instance
?
推荐答案
你设置另一个类符合 SocketDelegate
协议并将委托设置为该类。一旦你这样做, SocketDelegate
就可以调用委托方法,这些方法将传递给你设置委托的类。
You set another class to conform to the SocketDelegate
protocol and to set the delegate to that class. Once you do that, the SocketDelegate
can call delegate methods which will be passed to the class that you set the delegate as.
你的课程将是这样的:
class SocketManager {
static let instance: SocketManager
var socket = Socket()
weak var delegate: SocketDelegate?
}
extension SocketManager: SocketDelegate {
func someFunc() {
}
}
protocol SocketDelegate: class {
func someFunc()
}
class Socket: SocketDelegate { // so it conforms to the delegate
SocketManager.instance.delegate = self
}
这篇关于Swift - 为singleton设置委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文