tapwork
(Christian Menschel)
November 4, 2024, 1:03pm
1
Using a function like:
private func convertView<V: View>(view: V) -> some View {
view
}
returns AnyView
instead of the generic View like Text
Why is that?
But:
Using a Wraper View like
struct Wrapper<V: View>: View {
let view: V
var body: some View { view }
}
returns the generic View V
via the body.
any idea @xedin ?
xwu
(Xiaodi Wu)
November 4, 2024, 1:16pm
2
Can you provide a self-contained example of the behavior you're seeing? I cannot reproduce:
import SwiftUI
private func convertView<V: View>(_ view: V) -> some View {
view
}
print(type(of: convertView(Text(verbatim: "Hello"))))
// prints "Text"
tapwork
(Christian Menschel)
November 4, 2024, 1:51pm
3
sure
struct ContentView: View {
@State private var text = ""
var body: some View {
VStack(spacing: 40) {
demonstratingAnyView
demonstratingText
Text(text)
}
.padding()
}
private var demonstratingAnyView: some View {
VStack(spacing: 20) {
Button("Read with convert (AnyView)") {
readType(view: Text("Hello World"))
}
Button("Read without convert (Text)") {
readType(view: Text("Hello World"), convert: false)
}
}
}
private var demonstratingText: some View {
VStack {
Button("Read via Wrapper SwiftUI") {
text = String(describing: Wrapper(view: Text("Hello World")))
}
}
}
struct Wrapper<V: View>: View {
let view: V
var body: some View { view }
}
func readType<V: View>(view: V, convert: Bool = true) {
if convert {
let result = convertView(view: view)
text = String(describing: result)
} else {
text = String(describing: view)
}
}
private func convertView<V: View>(view: V) -> some View {
view
}
}
For me Swift Playgrounds (Swift 5.10 I believe) prints Text
but Xcode 16.1 (Swift 6.0.2) prints AnyView
.
UPDATE: But in Xcode 16.1 this actually only happen in debug build, release build prints Text
as expected. I've found this: Any info on the _typeEraser attribute .
tapwork
(Christian Menschel)
November 4, 2024, 7:21pm
5
thanks! the link explains it!