Typed parameter pack approach to function

I know this is swiftui, and Xcode, but I believe the question could be reduced to a non-swiftui generics/result builders example.

I have a project which contained a function which worked prior to Xcode 16.3. This was created in Dec/24. I was a bit surprised at the time that it worked, but shrugged and moved on; until 16.3 hit. I developed a manual unrolled work around which is really, really ugly and would require extensive unit tests for complete coverage. So I was wondering is there another solution similar to the more elegant approach. Briefly reviewing typed parameter packs, I came up empty. Is there such an approach, or should the original approach work?

Here is an isolated version of the problematic function:

import SwiftUI

struct ContainingProblemFunction<Comp:ViewModifier>: ViewModifier {

    public
    func body(content: Content) -> some View {
        EmptyView()
    }

    // WARNING: Rather doubtful this will work.
    @ViewBuilder
    private
    func apply(modifiers: [Comp], toContent content: some View) -> 
                                                                some View {
        if !modifiers.isEmpty,
           let next = modifiers.first {
            let newContent =
                ModifiedContent(content: content, modifier: next)
            if modifiers.count > 1 {
                let rest = [Comp](modifiers.dropFirst())
                apply(modifiers: rest, toContent: newContent)
            }
            else {
                newContent
            }
        }
        else {
            content
        }
    }
}
1 Like

If you use AnyView, then it's a reduce operation. I'm not thinking of a better way at the moment.

struct ModifierPack<each Modifier: ViewModifier>: ViewModifier {
  let modifier: (repeat each Modifier)

  func body(content: Content) -> some View {
    var anyView = AnyView(content)
    for modifier in repeat each modifier {
      anyView = .init(anyView.modifier(modifier))
    }
    return anyView
  }
}

extension View {
  func modifierPack<each Modifier: ViewModifier>(
    _ modifier: repeat each Modifier
  ) -> some View {
    self.modifier(ModifierPack(modifier: (repeat each modifier)))
  }
}

Thanks for the response Danny. Beyond the possible performance issues, the idea is to avoid AnyView use because of the way it hides the type.

What sort of interests me here is why the function worked with 16.2. From my uninformed reasoning, I don’t understand why it worked given the return of the dynamic if-else-if… type with contained nested subtypes. It is like I have access to a type constructor. I bet it would have failed at runtime if I passed in an array count of 100. Still pretty cool that it worked.