ios - Swift:如何将通用协议(protocol)作为另一个协议(protocol)的参数传递

标签 ios swift delegates protocols

我想将通用协议(protocol)作为另一个协议(protocol)的参数传递。

protocol OperationDelegate {
    associatedtype T
    func onOperationFinished(result:Array<T>)
    func onOperationError(error:OperationError, errorMessage:String)
}


protocol ResultDelegate {

    func findResult(query: String,odelegate: OperationDelegate<MyOwnDataType>)

}

如何将通用协议(protocol)作为另一个协议(protocol)的参数传递

我收到以下错误

Protocol 'OperationDelegate' can only be used as a generic constraint because it has Self or associated type requirements

最佳答案

protocol OperationDelegate {
    associatedtype T
    func onOperationFinished(result:Array<T>)
    func onOperationError(error: Error, errorMessage:String) 
}

protocol ResultDelegate {
    func findResult<OpDelegate: OperationDelegate>(query: String, odelegate: OpDelegate) 
}

//添加了一些 PlayGround 作品

    class ResultsFinder: ResultDelegate {



    func findResult<OpDelegate>(query: String, odelegate: OpDelegate) where OpDelegate : OperationDelegate {

        print(#function)
        // Do some operations
        let s1 = Student()
        s1.name = "one"
        let s2 = Student()
        s2.name = "two"

        let addressList = [s1,s2]
        odelegate.onOperationFinished(result: addressList as! [OpDelegate.T])

    }
}

还有

class ResultDisplay: OperationDelegate {

    typealias T = Student

    func onOperationFinished(result: [Student]) {
        // Display address
          print(#function)
    }


    func onOperationError(error: Error, errorMessage: String) {
        // Display error
          print(#function)
    }

}

类主函数{

let resultDisplay = ResultDisplay()
let finder = ResultsFinder()
func start() {

      print(#function)
    finder.findResult(query: "Sridhar", odelegate: resultDisplay)

}

}

let main = Mainfunction()
main.start()

关于ios - Swift:如何将通用协议(protocol)作为另一个协议(protocol)的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55137499/

相关文章:

ios - 使用 UISearchBar 在 Core Data 中搜索 NSDates(使用 NSDateFormatter 的字符串)

ios - 如何从数组中只传递一个键值对?

swift - 从自定义 imageView 类执行 segue?

ios - iOS 中的 MVVM 模式

swift - AVPlayer 不播放音频

C# + 重写委托(delegate)

ios - 仅在 iPhone 4S 上对委托(delegate)进行错误访问

ios - Swift:尝试附加随机数组元素时获取 EXC_BAD_INSTRUCTION

c++ - 允许在没有 Active Directory 信任的情况下进行 winhttp 委派

ios - ScrollView 中没有可见部分的按钮