我有一个“ItemContainer”协议(protocol)和符合该协议(protocol)的 UIViewController 子类“ItemPageController”。
我还有一个“ItemContainerControllerFactory”协议(protocol)和一个符合该协议(protocol)的结构。
问题:我希望创建一个返回适当的 ItemControllerControllerFactory 子类型的方法。但是,我收到以下编译器错误:“无法将类型 ItemPageControllerFactory 的返回表达式转换为返回类型 T”
protocol ItemContainer {
func navigateToItem(item:Item)
}
class ItemPageController : UIViewController, ItemContainer {
func navigateToItem(item:Item) { ... }
}
protocol ItemContainerControllerFactory {
associatedtype ContainerType : UIViewController, ItemContainer
func itemContainerController() -> ContainerType
}
struct ItemPageControllerFactory: ItemContainerControllerFactory {
typealias ContainerType = ItemPageController
func itemContainerController() -> ContainerType {
return ContainerType()
}
}
//Goal: Be able to return different ItemContainerControllerFactory depending on some logic... (Currently hard coded to ItemPageControllerFactory)
func itemContainerFactory<T:ItemContainerControllerFactory>() -> T {
return ItemPageControllerFactory() //COMPILER ERROR: "Cannot convert return expression of type ItemPageControllerFactory to return type T"
}
对我做错了什么有什么想法吗?
最佳答案
为了像现在这样使用协议(protocol)创建一个通用实例,您需要在协议(protocol)中有一个初始化程序
像这样:
protocol TestProtocol {
init()
}
func create<T: TestProtocol>() -> T {
return T()
}
关于ios - Swift 2.2 泛型 : "Cannot convert return expression of type ItemPageControllerFactory to return type T",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36895539/