首页 > 解决方案 > SwiftUI:为什么 UIHostingController(rootView:) 可以传递 nil 值?

问题描述

在 Xcode 游乐场:

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


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

请注意 func UIHostingController(rootView: ) 签名不允许传递 nil 值:

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

    public init(rootView: Content)
}

那么为什么我可以将 nil 传递给 UIHostingController(rootView:) ???

谢谢 ;)

更新:

所以我尝试写一些类似 UIHostingController 的类:</p>

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
    }
}

但是当我创建一个容器实例时,会发生一些错误:

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

编译器抱怨我:</p>

参数类型“A?” 不符合预期的“P”类型

那么 UIHostingController 是如何做到的呢???

标签: swiftui

解决方案


在下面的代码中,确实 V0 为 nil。但是,重要的是要注意 v0 是 Text? 类型。

let view = UIHostingController(rootView: v0)

即使下面的行不起作用

let view = UIHostingController(rootView: nil)

这行得通。

let view = UIHostingController<Text?>(rootView: nil)

要修复错误“通用类 'Container' 需要 'A?' 符合'P'”,容器类可以更新如下

class Container<T>: X where T: P{
    init(a:T?){
        if let a = a {
            print(a.name)
        }
    }
}

推荐阅读