swiftui - 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 是如何做到的呢???
解决方案
在下面的代码中,确实 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)
}
}
}
推荐阅读
- c# - 如何使用嵌套对象作为 Dapper 的查询参数
- kubernetes-helm - 使用 Velero 备份/恢复 Rancher 目录应用程序
- python - PostgreSQL 11:错误 [57P03]:致命:数据库系统处于恢复模式
- modelica - 欧拉求解器在 Dymola 事件附近的时间步长
- java - 春季启动应用程序,组件扫描缺少一些@Component
- python - 如何使用“字符串的切片”.isnumeric() 的条件迭代 df 列
- python - 为什么当我的机器人通过网站的 html 代码抓取元素时,我无法将其输入信用卡输入部分?
- python - 使用CNN(Tensorflow)和深度学习对芙蓉植物的雄性和雌性部分进行图像分类
- java - 必须编写一个程序,在不使用 if 语句、循环或数组的情况下给我偶数的总和,我应该如何在 java 中做到这一点?
- javascript - 基于onchange函数多次调用HTTP请求