[英]How can have an instance or a return type of a generic type conforming to a protocol with associated value
[英]How can assing generic (associated type require) protocol as delegate to any controller?
我有一個協議,其關聯類型名為MessageType。
protocol MessageProtocol: class {
associatedtype MessageType
func sendMessage(_ with: MessageType)
}
然后在控制器中實現
extension MainController: MessageProtocol{
typealias MessageType = String
func sendMessage(_ with: MessageType) {
// sending message
}
}
我的目的是在下面的其他控制器中將協議用作委托。
final class AnotherController {
weak var messagerDelegate: MessageProtocol?
...
}
但是我得到了錯誤
協議“ MessageProtocol”只能用作通用約束,因為它具有“自身”或相關的類型要求
有什么辦法可以解決這個錯誤?
我正在閱讀有關這種情況的Big Nerd Ranch博客文章。 https://www.bignerdranch.com/blog/why-associated-type-requirements-become-generic-constraints/
我已經了解了這種情況,但不知道如何實現?
謝謝,
我這樣處理。
final class AnotherController<T: MessageProtocol> where T.MessageType == String {
weak var messagerDelegate: T?
...
}
如果我想以編程方式創建anotherController實例,則可以這樣創建。
let instance = AnotherController<MainController>(frame: CGRect.zero)
instance.delegate = self
...
因為MainController
對MessageProtocol
從
extension MainController: MessageProtocol{}
可能這不是普遍情況,但對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.