为什么不能在 SwiftUI 视图中迭代枚举数据?

Mat*_*ift 18 macos enums ios swift swiftui

假设我有一些枚举,Channel填充了示例属性数据:

enum Channel: CaseIterable {
  case abc
  case efg
  case hij
  
  var name: String {
    switch self {
    case .abc:  return "ABC"
    case .efg:  return "EFG"
    case .hij:  return "HIJ"
    }
  }
}

extension Channel: Identifiable {
  var id: Self { self }
}
Run Code Online (Sandbox Code Playgroud)

以及一些视图实现来填充所述内容:

struct ChannelHome: View {
  var body: some View {
    VStack {
      ForEach(Channel.allCases) { channel in
        NavigationLink(destination: ChannelDetail(channel)) {
          Text(channel.name)
        }
      }
    }
  }
}   // big closure yikes
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用?这是因为枚举没有静态属性并且 SwiftUI 是声明性的吗?有办法解决这个问题吗?例如:

struct ChannelData {
  static let channels: [Channel] = [.abc, .efg, .hij]
  // or
  static func getChannels() -> [Channel] {
    var channelArray: [Channel]
    for channel in Channel.allCases {
      channelArray.append(channel)
    }
    return channelArray
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,理想的是,是否有更好的实践来在 SwiftUI 视图中呈现此类小型数据集?我喜欢能够在运行时(更接近生产阶段)进行整体调试时实现属性的可视化 UI。

我提前为这个问题道歉,我刚刚开始使用 SwiftUI。

use*_*ser 26

这里有两种简单的方法,但不确定哪些方法对您有帮助,因为使用枚举您无法更新 ForEach 元素,但它有一个显示数据的用例!

第一种没有任何可识别 ID 的方法:

struct ContentView: View {        
    var body: some View {            
        ForEach(TestEnum.allCases, id: \.rawValue) { item in                 
            Text(item.rawValue)                
        }
    }        
}

enum TestEnum: String, CaseIterable { case a, b, c }
Run Code Online (Sandbox Code Playgroud)

使用符合 Identificate 协议的 Identificate id,你, id: \.id甚至可以削减:

struct ContentView: View {
    var body: some View {
        ForEach(TestEnum.allCases, id: \.id) { item in
            Text(item.rawValue)
        }
    }
}

enum TestEnum: String, CaseIterable, Identifiable { case a, b, c
    var id: String { return self.rawValue }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*ift 9

要么 Xcode 因缓存错误而挂起,要么我是个傻瓜(可能是后者)。无论如何,这个问题似乎已经通过以下对枚举的可识别扩展以及良好的派生数据清除和清理得到了解决:

extension Channel: Identifiable {
  var id: Self { self }
}
Run Code Online (Sandbox Code Playgroud)

我似乎把这个问题与我经常遇到的另一个长期问题混淆了;主要是关于枚举及其对存储静态数据的厌恶(这只是其快速和精简结构的本质)。