'm trying to write my own stack, and the issue I'm encountering is how to get the child content of a ForEach.
//
// ContentView.swift
// test
//
// Created by cnsinda on 2025/10/18.
//
import SwiftUI
public struct MyStack<Content: View>: View {
var content: [Content]
public init(@MyStackBuilder<Content> content: @escaping () -> [Content]) {
self.content = content()
}
public var body: some View {
VStack {
// I expect to get 9, but it always returns 1.
Text("count:\(content.count)")
}
}
}
@resultBuilder public enum MyStackBuilder<Value: View> {
static func buildBlock() -> [Value] {
[]
}
public static func buildBlock(_ components: Value...) -> [Value] {
components
}
public static func buildBlock(_ components: [Value]...) -> [Value] {
components.flatMap {
$0
}
}
// hit
public static func buildExpression(_ expression: Value) -> [Value] {
[expression]
}
public static func buildArray(_ components: [[Value]]) -> [Value] {
components.flatMap { $0 }
}
static func buildFinalResult(_ components: [Value]) -> [Value] {
components
}
public static func buildExpression(_ expression: ForEach<[Int], Int, Value>) -> [Value] {
expression.data.flatMap { index in
[expression.content(index)]
}
}
public static func buildEither(first: [Value]) -> [Value] {
return first
}
public static func buildEither(second: [Value]) -> [Value] {
return second
}
public static func buildIf(_ element: [Value]?) -> [Value] {
return element ?? []
}
}
struct ContentView: View {
var body: some View {
ZStack {
MyStack {
ForEach([100, 110, 120, 130, 140, 150, 160, 170, 180], id: \.self) {
item in
Rectangle().frame(width: item, height: 20).padding(10)
}
}
}
.frame(width: 600, height: 600)
}
}
My expectation is to get each individual Rectangle(), but the actual result is that the entire ForEach is treated as a single View. What should I do?