protocol Readable {}
extension Readable {
func text() -> String? {
"in protocol"
}
}
struct Book: Readable {
func text() -> String {
"in struct"
}
}
let book: Book? = Book()
print(type(of: book?.text))
print(type(of: book!.text))
print(book?.text())
print(book!.text())
output is:
Optional<() -> String>
() -> String
Optional("in protocol")
in struct
sample code above. Why two func is the same, but print results are different
Anyone have idea?
I adjust this will always call from struct
CodePudding user response:
You print type
of text()
method, so you get a signature.
Take a look at this documentation:
- https://docs.swift.org/swift-book/LanguageGuide/Functions.html ("Function Types" chapter)
- https://developer.apple.com/documentation/swift/type(of:)
Two last print sentences show value produced by that function.
CodePudding user response:
The Readable.text()
method is a default implementation for the protocol, meaning that it is implemented for a conforming object if it doesn't provide its own text()
method.
Default implementations can also be a bit unpredictable. In this case, your Book
object implements its own text()
method, so the protocol's default implementation should not be called. However, in print(book?.text())
, you are actually calling the method on an Optional containing the Book
object. The optional does not provide its own text()
implementation (even though the containing book object does), so the default implementation is called.
I believe default implementations also make your code less efficient (because it requires dynamic dispatching), so for these reasons and more I try to avoid them when I can.