There is one big thing that confuses me about view types in SwiftUI:
They don't seem to conform to the View protocol, but somehow, they mysteriously do.
Take the Text type for example. It's defined as follows:
public struct Text : Equatable { ... }
I can't find any public extension that adds conformance to the View protocol, like
extension Text: View { ... }
and the Relationships section in the official documentation simply states:
Conforms To: Equatable
Nothing more, that's all.
Yet, I can return an instance of Text where some View is required, for example:
var body: some View {
Text("I'm a View, I swear!")
}
If Text didn't conform to View, this wouldn't be possible and throw a compiler error.
(some View is an opaque result type which means it's a specific type with an identity, but one that conforms to View.)
So how is this possible?
This question was asked on June 6, 2019, during WWDC, when we only had the first beta of Xcode 11 and SwiftUI. So answering this question correctly requires access to that version of SwiftUI. You can download Xcode 11 beta 1 here. (Thank you, xcodereleases.com!) You are in for an adventure trying to unpack the archive, though, because (I think) it was signed with a certificate that has since expired. I resorted to black magic (stepping through the
xipcommand in LLDB and modifying memory at a key moment to subvert the certificate verification). You could perhaps just set your system time back to June 6, 2019 before unpacking.Anyway, here's the secret to understanding why
Textdidn't appear to conform toView: Xcode, and Apple's documentation generator, intentionally omit identifiers in the SDK that start with_.So if you want to see the full public declaration of a type, you cannot rely on Xcode or the documentation to show it to you. Instead, you have to dig up the
.swiftinterfacefile for the module. For SwiftUI, you can find it here, relative to theXcode.appdirectory:In the Xcode 11 beta 1 version of that file, you won't find a direct conformance
Text: View. Instead, you will find this:And you will find that
_UnaryViewis a sub-protocol ofView:So, in Xcode 11 beta 1 and the corresponding iOS, macOS, tvOS, and watchOS betas,
Textconforms toViewindirectly, through its conformance to_UnaryView. Since_UnaryViewis part of the SDK and begins with_, Xcode and the Apple documentation hide that symbol. So you can't see the conformance through normal methods.At some later point (but still, I believe, during the Xcode 11.0 beta period), Apple eliminated the
_UnaryViewprotocol and madeTextconform directly toView. So if you check the SwiftUI.swiftinterfacefile in Xcode 11.4 (the current version as I write this), you'll find this: