[英]Why SwiftUI's View Protocol use PAT?
View
protocol is defined like this: View
协议的定义如下:
public protocol View : _View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required `body` property.
associatedtype Body : View
/// Declares the content and behavior of this view.
var body: Self.Body { get }
}
so View
is now a PATed protocol, which can't be used as a return type directly, though swift 5.1's opaque return type can handle this, but why declare a associatedtype Body : View
, not var body: View { get }
directly? 因此, View
现在是PATed协议,尽管swift 5.1的不透明返回类型可以处理此类型,但它不能直接用作返回类型,但是为什么要声明一个associatedtype Body : View
而不是var body: View { get }
直接?
Because if it is just a var body: Self.Body { get }
- your entity, that implements View
protocol, will not know the type of the body
. 因为如果只是一个var body: Self.Body { get }
-实现View
协议的您的实体将不知道body
的类型。
struct MyView: View {
var body: MyAnotherView {
//implementation...
}
}
This code will not compile and you would have to write this: 该代码将无法编译,您必须编写以下代码:
struct MyView: View {
var body: View {
//implementation...
}
}
And I think behind the scenes SwiftUI has to know the exact type of a View
, not just a protocol 而且我认为,在幕后,SwiftUI必须知道View
的确切类型,而不仅仅是协议
Prior to SwiftUI Swift doesn't allow us to use protocols with associated types as return types but We can use “regular” protocols. 在SwiftUI之前,Swift不允许我们将具有关联类型的协议用作返回类型,但是我们可以使用“常规”协议。 Compiler let you restrict by showing below error: 编译器让您通过显示以下错误进行限制:
“Protocol can only be used as a generic constraint because it has Self or associated type requirements.” “协议只能用作通用约束,因为它具有Self或关联的类型要求。”
What does it mean? 这是什么意思?
Compiler cannot infer the associated type from this definition and the return type would be incomplete. 编译器无法从此定义推断关联的类型,并且返回类型将不完整。
Whenever we call the that function it always return different concrete type instead if same concrete type. 每当我们调用那个函数时,它总是返回不同的具体类型,而不是相同的具体类型。
To avoid the different concrete type as return type at each call we use some keyword as opaque return type. 为了避免在每次调用时使用不同的具体类型作为返回类型,我们使用一些关键字作为不透明的返回类型。
Opaque return type: 不透明返回类型:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.