Swift - 为singleton设置委托

时间:2015-04-09 10:32:18

标签: ios swift singleton

我有这样的事情:

class SocketManager {
    static let instance: SocketManager
    var socket = Socket()
}

extension SocketManager: SocketDelegate {
    func someFunc() {
    }
}

Socket是一个拥有protocoldelegate

的类
protocol SocketDelegate: class {
    func someFunc()
}

class Socket {
    weak var delegate: SocketDelegate?
}

如何将socket.delegate设为SocketManager.instance

1 个答案:

答案 0 :(得分:1)

您设置另一个类以符合SocketDelegate协议并将委托设置为该类。执行此操作后,SocketDelegate可以调用委托方法,这些方法将传递给您将委托设置为的类。

你的课程将是这样的:

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
}