如何为全局调用创建枚举预期的硬编码字符串

How to create an enum intended hardcoded strings for global calls

我想创建一个用于在 SwiftUI 中存储硬编码字符串的枚举。实现这个的最佳方法是什么?

我已经尝试创建一个 @BindableObject,这让事情变得有点复杂。我也曾尝试将枚举创建为扩展、单独文件中的单独模型,或者在结构外部的 and/or 内,但没有任何运气。

此外,我需要能够使用这些硬编码点从 ItemRow 中调用的 JSON 文件中调用特定信息。我想最好的方法是创建一个单独的文件,但我停留在第一级。

下面是我要创建的枚举

enum Sections: String {
    case one = "Header 1"
    case two = "Header 2"
    case three = "Header 3"
    case four = "Header 4"
}

这是我的部分:

Section(header: Sections.one) {
    Section(header: Sections.two.font(.headline)) {
        ForEach(userData.items) { item in
            NavigationLink(destination:
                ItemDetailView(userData: UserData(), item: item)) {
                    ItemRow(item: item)
        }
    }
}

这是我遇到的错误:

Referencing initializer 'init(header:content:)' on 'Section' requires that 'ItemListView.Sections' conform to 'View'

您的代码有几个问题:

  1. 要从枚举中获取字符串,您需要使用 rawValue。即Sections.one.rawValueSections.two.rawValue

  2. Section header 参数需要一个视图,而不是一个字符串。所以你应该改变:

Section(header: Sections.one)

Section(header: Text(Sections.one.rawValue))

最后,

  1. 字体修饰符需要应用于文本视图,而不是字符串,因此您还需要更改:
Section(header: Sections.two.font(.headline))

Section(header: Text(Sections.two.rawValue).font(.headline))