MST

星途 面试题库

面试题:Swift插件化架构中的模块通信方式

在Swift插件化架构设计中,不同插件模块之间通常需要进行通信。请列举至少两种常见的模块通信方式,并简述每种方式在Swift中的实现要点。
41.2万 热度难度
编程语言Swift

知识考点

AI 面试

面试题答案

一键面试
  1. 代理模式
    • 实现要点
      • 首先定义一个协议,协议中声明需要通信的方法。例如:
protocol PluginCommunicationProtocol {
    func sendData(data: String)
}
 - 在需要接收数据的插件模块中,定义一个遵循该协议的代理属性,并且实现协议方法。例如:
class ReceiverPlugin {
    var delegate: PluginCommunicationProtocol?
    func someFunction() {
        delegate?.sendData(data: "Hello from Receiver")
    }
}
 - 在发送数据的插件模块中,设置代理为接收模块的实例,并调用代理方法发送数据。例如:
class SenderPlugin {
    let receiver = ReceiverPlugin()
    init() {
        receiver.delegate = self
    }
}

extension SenderPlugin: PluginCommunicationProtocol {
    func sendData(data: String) {
        print("Received data: \(data)")
    }
}
  1. 通知中心(NotificationCenter)
    • 实现要点
      • 在发送数据的插件模块中,使用NotificationCenter.default.post方法发送通知,并携带需要传递的数据。例如:
class SenderPlugin {
    func sendData() {
        let userInfo = ["data": "Some important data"]
        NotificationCenter.default.post(name: Notification.Name("PluginDataNotification"), object: nil, userInfo: userInfo)
    }
}
 - 在接收数据的插件模块中,使用`NotificationCenter.default.addObserver`方法注册监听通知,并在回调方法中处理数据。例如:
class ReceiverPlugin {
    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(receiveData(_:)), name: Notification.Name("PluginDataNotification"), object: nil)
    }

    @objc func receiveData(_ notification: Notification) {
        if let userInfo = notification.userInfo, let data = userInfo["data"] as? String {
            print("Received data: \(data)")
        }
    }
}
  1. 闭包回调
    • 实现要点
      • 在接收数据的插件模块中,定义一个闭包属性用于接收数据。例如:
class ReceiverPlugin {
    var dataReceivedClosure: ((String) -> Void)?
    func someFunction() {
        dataReceivedClosure?("Data from Receiver")
    }
}
 - 在发送数据的插件模块中,设置闭包并在闭包中处理接收到的数据。例如:
class SenderPlugin {
    let receiver = ReceiverPlugin()
    init() {
        receiver.dataReceivedClosure = { data in
            print("Received data: \(data)")
        }
    }
}