fankibiber
fankibiber

Reputation: 809

How to create an enum intended hardcoded strings for global calls

I want to create an enum for storing hardcoded strings in SwiftUI. What is the best way to implement this?

I have already tried creating a @BindableObject, which made things quite a bit complicated. I have also tried creating the enum as an extension, separate model in a separate file, or within and/or outside the struct, but no luck whatsoever.

Also following this, I need to be able to use these hardcoded points to call specific information from the JSON file called in ItemRow. Best way to do this is to create a separate file I guess, but I'm stuck at the first level.

Below is the enumeration I'm trying to create

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

And this is my Section:

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)
        }
    }
}

This is the error I'm getting:

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

Upvotes: 0

Views: 428

Answers (1)

kontiki
kontiki

Reputation: 40509

There are several problems with your code:

  1. To get the string from your enum, you need to use rawValue. That is, Sections.one.rawValue, Sections.two.rawValue, etc.

  2. The Section header parameter requires a View, not a String. So you should change:

Section(header: Sections.one)

with

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

And finally,

  1. The font modifier needs to be applied to a Text view, not a string, so you need to also change:
Section(header: Sections.two.font(.headline))

to

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

Upvotes: 1

Related Questions