在Xcode游乐场:
func makeView<T:View>(v: T) -> T?{
nil
}
let v0 = makeView(v: Text(""))
let view = UIHostingController(rootView: v0)注意,func UIHostingController(rootView:)签名不允许传递零值:
open class UIHostingController<Content> : UIViewController where Content : View {
public init(rootView: Content)
}那么,为什么我可以将零传递给UIHostingController(rootView:)?
(谢谢;)
更新:
所以我试着写一些类似于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
}
}但是,当我创建容器实例时,会发生一些错误:
let p = Container(a: A(name: ""))编译器抱怨我:
参数类型'A?‘不符合预期类型'P‘
那么UIHostingController是怎么做到的呢?
发布于 2020-07-05 05:19:16
在下面的代码中,V0确实是零。但是,需要注意的是,v0是文本类型的?
let view = UIHostingController(rootView: v0)即使在线下不起作用
let view = UIHostingController(rootView: nil)这个很管用。
let view = UIHostingController<Text?>(rootView: nil)要修复错误“泛型类‘容器’要求'A?‘符合’P‘,容器类可以更新如下
class Container<T>: X where T: P{
init(a:T?){
if let a = a {
print(a.name)
}
}
}https://stackoverflow.com/questions/62734995
复制相似问题