我正在尝试进行以下代码编译。 基本上我希望对象符合多种协议,例如将不同API组暴露给app的不同部分的网络服务(例如:登录API到loginController,共享API到shareController)
+
我希望使用networkXProvider协议注入此服务,例如实现依赖注入(例如我想传递给LoginController一个采用LoginControllerProvider和FetchingUsersFromDBProvider的注入):
protocol MyAccountCommunicator {
func getAccountData() -> String
}
protocol EventsCommunicator {
func getEvents() -> String
}
class NetworkManager: MyAccountCommunicator, EventsCommunicator {
func getAccountData() -> String {
return "Accounts"
}
func getEvents() -> String {
return "Events"
}
}
protocol MyAccountCommunicatorProvider {
var networkCommunicator: MyAccountCommunicator { get }
}
protocol EventsCommunicatorProvider {
var networkCommunicator: EventsCommunicator { get }
}
class Injector: MyAccountCommunicatorProvider, EventsCommunicatorProvider {
var networkCommunicator: NetworkManager = NetworkManager()
}
Playground因以下错误而失败:
错误:strings.playground:29:7:错误:输入' Injector'才不是 遵守协议' MyAccountCommunicatorProvider'注射器: MyAccountCommunicatorProvider,EventsCommunicatorProvider { ^
strings.playground:30:9:注意:候选人有不匹配的类型 '网络管理器' var networkCommunicator:NetworkManager = NetworkManager() ^
错误:strings.playground:29:7:错误:输入' Injector'才不是 符合协议' EventsCommunicatorProvider'注射器: MyAccountCommunicatorProvider,EventsCommunicatorProvider { ^
strings.playground:30:9:注意:候选人有不匹配的类型 '网络管理器' var networkCommunicator:NetworkManager = NetworkManager()
环境:swift4,XCode9
答案 0 :(得分:0)
为什么需要MyAccountCommunicatorProvider和EventsCommunicatorProvider协议?如果将它们组合成一个怎么办?
protocol CommunicatorProvider {
var networkCommunicator: NetworkManager { get }
}
class Injector: CommunicatorProvider {
var networkCommunicator = NetworkManager()
}
答案 1 :(得分:0)
protocol MyAccountCommunicator {
func getAccountData() -> String
}
protocol EventsCommunicator {
func getEvents() -> String
}
protocol MyAccountCommunicatorProvider {
var accountCommunicator: MyAccountCommunicator { get }
}
protocol EventsCommunicatorProvider {
var eventCommunicator: EventsCommunicator { get }
}
class NetworkManager: MyAccountCommunicator, EventsCommunicator {
func getAccountData() -> String {
return "Accounts"
}
func getEvents() -> String {
return "Events"
}
}
class Injector: MyAccountCommunicatorProvider, EventsCommunicatorProvider {
var networkManager = NetworkManager()
var accountCommunicator: MyAccountCommunicator {
return networkManager
}
var eventCommunicator: EventsCommunicator {
return networkManager
}
}
答案 2 :(得分:0)
您可以这样使用:
protocol MyAccountCommunicatorProvider {
var networkCommunicator1: MyAccountCommunicator { get }
}
protocol EventsCommunicatorProvider {
var networkCommunicator2: EventsCommunicator { get }
}
class Injector: MyAccountCommunicatorProvider, EventsCommunicatorProvider {
var networkCommunicator: NetworkManager = NetworkManager()
lazy var networkCommunicator1: MyAccountCommunicator = {
return networkCommunicator
}()
lazy var networkCommunicator2: EventsCommunicator = {
return networkCommunicator
}()
}