I tried implementing a function that returns an instance conforming to a protocol.
Here is some code that I tried:
protocol MyProtocol {
func doSomething()
}
extension MyProtocol {
func doSomething() {
print("Default implementstion")
}
}
struct MyStruct1 : MyProtocol {
func doSomething() {
print("MyStruct1 implementation")
}
}
struct MyStruct2 : MyProtocol {
// empty
}
func createStruct(_ val : Bool) -> MyProtocol {
if val {
return MyStruct1()
} else {
return MyStruct2()
}
}
// The following crashes:
let product = createStruct(false)
product.doSomething()
struct Wrapped {
let value : MyProtocol
}
func createWrapped(_ val : Bool) -> Wrapped {
if val {
return Wrapped(value: MyStruct1())
} else {
return Wrapped(value: MyStruct2())
}
}
// The following works:
let wrapped = createWrapped(false)
wrapped.value.doSomething()
So createStruct
version crashes whereas createWrapped
works. I tried changing return type of createStruct
to any MyProtocol
, but that does not have any positive effect.
Why does createStruct
version crash?
Why compiler not give any kind of warning or error that code is not going to work?
New contributor
rooperi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3