Ditto on what Florian S said, you should use a ternary as inline conditionals on view modifiers can lead to many issues, but... they can be useful sometimes as well, so if you want to use inline conditional operations on view modifiers do this.
Add an some extensions to view.. you don't need both of these but depending on how you want to to use it, each has their strengths
extension View {
@ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
if (condition) {
transform(self)
} else {
self
}
}
@ViewBuilder func `ifInline`<Content: View>(_ condition: @autoclosure () -> Bool, transform: (Self) -> Content) -> some View {
if condition() {
transform(self)
} else {
self
}
}
}
then, on the view you want to use the extension with do something like this
ForEach(values: self.multiDevice ? devices : device) { device in
Group {
ForEach(values: ColorScheme.allCases) { scheme in
self.viewToPreview
.background(Color.backgroundColor)
.colorScheme(scheme)
.previewDevice(PreviewDevice(rawValue: device))
.previewDisplayName("\(displayName) - \(scheme.previewName) - \(device)")
.if(self.wrapped) { view in
view.previewLayout(.sizeThatFits)
}
}
}
}
To use the second extension, the '.if' would turn into a '.ifInline'.
A small note, this use case is from a GenPreviews class I make in my projects to more easily show canvas previews on various devices and color schemes with a descriptive title I can provide a name for from the Provider and some bools I can pass to show either one device or multiple from two lists of options I include as well as wrapping or showing the view on a device preview.
The reason I bring this up is because this use case not only isn't used in production runtime, but isn't even included when compiling a release... which goes back to my first statement that I agree with Florian S. I have used inline conditionals on view modifiers for running code before, but it is not good practice and shouldn't be done unless circumstances require and permit it. A ternary operator for your situation would be the best approach.