Opaque return types
紀錄 Opaque types 的一些資訊。
struct ContentView: View {
var body: some View {
Text("hello world")
}
}
public protocol View {
/// The type of view representing the body of this view.
associatedtype Body : View
/// The content and behavior of the view.
@ViewBuilder var body: Self.Body { get }
}
此 ContentView 定義 body 的 Read-Only computed properties,getter 回傳 some View
,某個符合 View protocol 的型別,稱為 Opaque type。
官網定義:
A function or method with an opaque return type hides its return value’s type information. Instead of providing a concrete type as the function’s return type, the return value is described in terms of the protocols it supports. Hiding type information is useful at boundaries between a module and code that calls into the module, because the underlying type of the return value can remain private. Unlike returning a value whose type is a protocol type, opaque types preserve type identity—the compiler has access to the type information, but clients of the module don’t.
由以上說明可知,Opaque return type 可以隱藏型別資訊。
我們可以藉著以下方法來得知真實的 body 型別資訊。在這個例子中,真實回傳的型別是 VStack<Button<Text>>
。
struct ContentView: View {
var body: some View {
VStack {
Button("print my type") {
print(type(of: self.body))
// VStack<Button<Text>>
}
}
}
}