SwiftUI: Why UIHostingController(rootView:) can pass nil value?

In Xcode playground :

func makeView<T:View>(v: T) -> T?{
    nil
}


let v0 = makeView(v: Text(""))
let view = UIHostingController(rootView: v0)

note that func UIHostingController(rootView: ) signature not allowed pass nil value:

open class UIHostingController<Content> : UIViewController where Content : View {

    public init(rootView: Content)
}

So why I can pass nil to UIHostingController(rootView:) ???

thanks :wink:

Update:

So I try to write some one like class UIHostingController:

protocol P{
    var name: String {get}
}

class Container<T> where T: P{
    init(a:T){
        print(a.name)
    }
}

struct A: P {
    var name:String
    
    init?(name:String) {
        
        if name.isEmpty{
            return nil
        }
        
        self.name = name
    }
}

but when I create a instance of Container, some wrong happens:

let p = Container(a: A(name: ""))

compiler complain me :

Argument type ‘A?’ does not conform to expected type ‘P’

So how UIHostingController did that???

It’s not about UIHostingController. It’s because optional Views conform to View:

extension Optional : View where Wrapped : View {
    /// The type of gesture representing the body of `Self`.
    public typealias Body = Never
}

As such, you can write this, for example:

let v0: some View = makeView(v: Text(""))

I think the motivation was that it makes it much easier to use function builders, where nil views won’t render.

I got it!!! Thanks a lot!!! :joy:

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.