I've read the In swift, why can't I instantiate a protocol when it has an initialiser?
My question is focused on why the compiler can't look into your default implementation and initialize an object based on that?
protocol ViewModel {
var radius: Int { get }
init()
}
extension ViewModel {
var radius: Int { return 2}
init() {}
}
let v = ViewModel() // ERROR:
Protocol type 'ViewModel' cannot be instantiated
Question1:
Why doesn't Swift allow a vanilla initialization of a protocol? Why does it have to be tied to a concrete type?
I get it that it's not a concrete type. But why doesn't the compiler allow you to just create a type that is nothing but the protocol in its default value?! Is it because the compiler is like hey listen while I can either think of you as an interface/protocol or as an actual type. I can't think of you as both!? You're either something real in memory or just a blue-print.
If the language could have checked to see if an extension has provided implementation for all requirements then would it have made sense to allow initializing that as a special case? (I understand that it doesn't, but wondering is that the only thing needed to get this to work) Or even then this would have not made sense. If so why?
Additionally I tried do this instead:
protocol ViewModel {
var radius: Int { get }
init()
}
extension ViewModel {
var radius: Int { return 2}
init() {
self.init() // Line A:
}
}
struct ReallyNothing: ViewModel {}
let v = ReallyNothing()
If I comment out LineA then I'll get an error of
'self.init' isn't called on all paths before returning from initializer
Question2:
WHY? why does the init
have to call self.init()
it seems a bit like a recursive loop.