1

I have a simple dictionary such as follows:

let testDict = [
    "a": "apple",
    "b": "banana",
    "c": "cherry"
]

To render it in a view, using an answer from SwiftUI iterating through dictionary with ForEach, I use:

ForEach(testDict.sorted(by: >), id: \.key) { key, value in
   Text(value)
}

and it works well enough. I would now like to filter the list with an if block as per SwiftUI: ForEach filters boolean .However, if I attempt to include an if block:

ForEach(testDict.sorted(by: >), id: \.key) { key, value in
   if key != "b" {
       Text(value)
   }
}

XCode seems to hang (it just takes a very long time) and eventually gives up with these messages:

Command CompileSwift failed with a nonzero exit code

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

at the very end of the ContentView struct. This is not very helpful, and I can’t see why it takes XCode so long to give up.

How do I include an if block in a ForEach ?

I real life, the dictionary comes from a CoreData model, but the above sample gives the same problems.

I am developing on XCode 12.1, targeting MacOS 10.15

Update

I have since had success with the following:

ForEach(testDict.filter({$0.key != "b"}).sorted(by: >), id: \.key) { key, value in
   Text(value)
}

Manngo
  • 14,066
  • 10
  • 88
  • 110
  • I tried this code and it worked perfectly fine for me. I'm using Xcode `Version 12.2 beta 3`. Does this simple example you gave work on its own? – George Oct 25 '20 at 00:21
  • @George_E I’ve dropped the sample into a Playground, and it immediately gives me the error `Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols`. – Manngo Oct 25 '20 at 01:18

1 Answers1

1

You need view in ForEach content, so use Group, like

ForEach(testDict.sorted(by: >), id: \.key) { key, value in
   Group {
     if key != "b" {
       Text(value)
     }
   }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thanks again for coming to the rescue. This explains why `if` works in some examples and not others. – Manngo Oct 25 '20 at 04:39