December 10, 2017
What’s the difference between interface and abstract class? I have heard this question on almost every interview, when last time I have looked for a job. In Swift, protocols are very close to Java/C# interfaces, and the can’t contain implementations.
protocol IListener {
var id : Int { get set }
mutating func setId(newId : Int) {
self.id = newId
}
}
Here Xcode throws a error:
error: protocol methods may not have bodies
But, as it turns out, it is possible to make protocol extensions, and that extension can have implementation:
protocol IListener {
var id : Int { get set }
}
extension IListener {
mutating func setId(newId : Int) {
self.id = newId
}
}
I have no idea, why it is so.
Another strange protocol limitation is that, if it use self
reference, it can be used only as a generic constraint. I.e., compilator deniedto compile this code:
protocol IListener : Hashable {
}
/* here some IListener implementation */
_ = Set<IListener> // error!
This is some strange things, that clearly demonstrated, that Swift is still in development mode. If extension protocol hack can be explained as some philosophy/architecture principle, but why protocol, that supposed to support hashing function, cannot be used as a container templat, is not clear for me.