ios - 如何快速实现方法参数中的协议?
问题描述
我想在其他方法参数中实现协议方法。
首先,我定义了一个包含方法的协议,
protocol MyProtocol {
func myProtocolFunc();
}
我做了一个以协议为参数的方法。
func myFunc(myProtocol : MyProtocol) {
. . .
}
当我使用这种方法时,我想覆盖protocolFunc()
.
myFunc( . . . )
protocolFunc()
我应该在我的方法中覆盖哪里myFunc()
?
ps 在 Kotlin 中,我是这样做的。
interface MyProtocol {
fun myProtocolFunc();
}
fun myFunc(myProtocol : MyProtocol) {
. . .
}
myFunc(object : MyProtocol {
override fun myProtocolFunc() {
. . .
}
})
我想在 swift 代码中做同样的事情。
=========================================
编辑:
实际上,我打算制作 Http Request 类。
从 Web 服务器获取一些数据后,我想在 ViewController 类中做一些工作。
因为 Http Request 在线程上运行,在从 web 服务器获取一些数据时,下一个关于数据的代码应该等待。
这是我的 Http 请求类,
class HttpConnector {
static let basicURL = "http://******"
static func getData(url : String, parameters : String, listener : UIModifyAvailableListener) {
if let fullURL = URL(string : "\(basicURL)\(url)") {
var request = URLRequest(url : fullURL)
request.httpMethod = "POST"
request.httpBody = parameters.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print("error = \(error!)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response!)")
}
if let result = String(data: data, encoding: .utf8) {
listener.taskCompleted(result: result)
}
})
task.resume()
}
}
}
protocol UIModifyAvailableListener {
func taskCompleted(result : String)
}
并且可以像这样在 ViewController 中调用此类
HttpConnector.getData("my_url", "my_parameter", [[some codes regarding UIModifyAvailableListener protocol]])
如果不能迅速完成,我想找一些替代方案。
解决方案
在您的协议中,将函数更改为函数的变量。
protocol UIModifyAvailableListener {
var taskCompleted : ((result : String) -> Void)? {get set}
}
然后在实现 UIModifyAvailableListener 的 HttpConnector 类中,添加以下内容:
var taskCompleted : ((result : String) -> Void)?
在 HttpConnector 类的方法中,您可以像这样调用 taskCompleted:
self.taskCompleted?(result)
然后在想要用 taskCompleted() 回调的调用代码中,只需设置 var:
myHttpConnector.taskCompleted =
{
print("Done!") // note if you want to reference self here, you'll probably want to use weakSelf/strongSelf to avoid a memory leak.
}
顺便说一句,如果您正在执行 MVVM,这是一个重要的模式,以便您的 ViewModel 可以回调 ViewController。由于 ViewModel 永远不会引用它的 ViewController,它所能做的就是拥有 ViewController 可以使用它想要调用的代码的闭包块设置的回调属性。通过使用协议,可以在对 ViewController 进行单元测试时模拟 ViewModel。:)