【问题标题】:ForEach on sorted dictionary: Xcode hangs on building with if block排序字典上的 ForEach:Xcode 使用 if 块构建
【发布时间】:2020-10-25 00:14:52
【问题描述】:

我有一个简单的字典,如下所示:

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

要在视图中呈现它,使用来自SwiftUI iterating through dictionary with ForEach 的答案,我使用:

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

而且效果很好。我现在想根据SwiftUI: ForEach filters boolean 使用if 块过滤列表。但是,如果我尝试包含if 块:

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

XCode 似乎挂起(只是需要很长时间)并最终放弃了这些消息:

Command CompileSwift 失败,退出代码非零

编译器无法在合理的时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式

在 ContentView 结构的最后。这不是很有帮助,我不明白为什么 XCode 需要这么长时间才能放弃。

如何在ForEach 中包含if 块?

我在现实生活中,字典来自 CoreData 模型,但上面的示例给出了同样的问题。

我正在 XCode 12.1 上开发,目标是 MacOS 10.15

更新

此后我在以下方面取得了成功:

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

【问题讨论】:

  • 我试过这段代码,它对我来说非常好。我正在使用 Xcode Version 12.2 beta 3。您给出的这个简单示例是否可以独立运行?
  • @George_E 我已经将样本放到 Playground 中,它立即给了我错误 Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

标签: xcode macos if-statement foreach swiftui


【解决方案1】:

您需要在 ForEach 内容中查看,因此请使用 Group,例如

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

【讨论】:

  • 再次感谢您前来救援。这解释了为什么 if 在某些示例中有效,而在其他示例中无效。
猜你喜欢
  • 2013-09-06
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 2021-08-08
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
相关资源
最近更新 更多