For rapid development‘s sake I made protocols called Message
and Socket
.
Follow by a real implementation and a mock one. Codes here:
// Procotols
protocol Message {
}
protocol Socket {
associatedtype T: Message
var messages: [T] { get }
}
// Real implementation
class RealMessage: Message {
}
class RealSocket: Socket {
private(set) var messages: [RealMessage] = []
}
// Mocks
class MockMessage: Message {
}
class MockSocket: Socket {
private(set) var messages: [MockMessage] = []
}
class VC {
// Error here: Protocol 'Socket' can only be used as a generic constraint because it has Self or associated type requirements
var socket: Socket = MockSocket()
// The only way I know to solve this is using the codes below:
// var socket: MockSocket = MockSocket()
}
My expectation:
Since I has two set of sockets, I wish I can switch environment between the mock and the real, which would be very nicely for development and debugging.
But there is an error in VC which stops me from accomplishment.
Any helps would be appreciated.
Don’t try to use a generic protocol this way. You could use an ordinary protocol, or a class so as to get inheritance, or a generic class if the generic part is important. But a protocol with a generic associated type is not itself a type.