Swift - set delegate for singleton

前端 未结 1 1304
难免孤独
难免孤独 2021-01-16 03:06

I have something like this:

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

extension SocketManager: SocketDelegate         


        
相关标签:
1条回答
  • 2021-01-16 04:08

    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.

    Your classes will be like this:

    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
    }
    
    0 讨论(0)
提交回复
热议问题