ForEach creates Views twice

Please take a look at the following simple SwiftUI View:

struct ContentView: View {
    var body: some View {
		 ForEach(1...1, id: \.self) { i in
			 subview(i)
		 }
   }

	func subview(_ i: Int) -> some View
	{
		print("creating subview \(i)")
		return Text("Hello, world!")
	}
}

When this View is displayed, all subviews are created twice, as the print statements show. (Unfortunately the Apple Developer Forums UI does not let me attach my sample Xcode project.) This happens on macOS 14.4.1.

Am I doing something wrong or is this a SwiftUI bug? (In a real-world application the View creation can be expensive…)

Replies

That's an old problem, as reported here: https://developer.apple.com/forums/thread/718281

That's caused by ForEach effectively, as no error here:

    var body: some View {
//        ForEach(1...1, id: \.self) { i in
            subview(0)
//        }

Some explanation here: it is due to the way SwiftUI performs init.

https://www.reddit.com/r/SwiftUI/comments/166m0tn/double_initiation_in_foreach_loop/

Adiitionally: Don't confuse running the body with "view creation". Running the body does not really show anything yet.