I've noticed that the body type of EmptyView is Never. But how does this conformance work?
For example, if I wanted to create my own "empty" view, I could do:
struct MyEmptyView: View {
var body: Never {
// What do I do here?
}
}
but then what would I do in the body? I can't use a trapping method because it will cause a crash. So how does SwiftUI do it? Does it put a call to fatalError() or something and dynamically remove the call at runtime?
I’d guess EmptyView has special consideration in SwiftUI. You could return an EmptyView value in your body? The return type would be some View. I’d guess it is not an appropriate idea though because you’d be doing something that isn’t view related in your view code.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension Never {
public typealias Body = Never
public var body: Never {
get
}
}
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension Never {
public typealias Value = Never
}
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension Never : View, _UnaryView {
}
Yeah I’ve looked at the swiftinterface file but I still don’t understand how the conformance is satisfied i.e I’m curious about what's happening in the body.
That's odd, now you made me even more curious. cc @jrose could the swiftinterface file have a bug a not expose a public var body: Body for some reason?
extension View where Self.Body == Swift.Never {
var body: Body {
get { /* fatalError? */ }
}
}
then what happens in the body of the getter? As the getter can't be empty or else you'd get Function with uninhabited return type 'Never' is missing call to another never-returning function on all paths.
That's weird though, I thought we don't need to return anything if the return value is Never. I recall switch working like that:
let never: Never! = nil
switch never as Never {
// done
}
But I guess it would be fine to use fatalError here. I would assume that SwiftUI would check if the view has a Body that is Never and use other parts of View to do other things. I know I can only speculate here.