Tyler Poland
Tyler Poland

Reputation: 52

Can a Swift enum be referenced as a variable?

I am centralizing all my application strings in enums, and these strings are all namespaced to the application feature in which they are used (example below).

When I attempt to store the enum in a variable (like var strings = Strings.Feature.SubFeature) and call it like strings.someStringValue, I get a Expected member name or constructor call after name type error.

Declaration:

enum Strings {
     enum Feature {
          enum Subfeature {
               static var someString: String { "some string".localizedLowerCase }
          }
     }
}

Callsite:

someLabel.text = Strings.Feature.Subfeature.string

Hoped-for behavior:

var strings = Strings.Feature.Subfeature
someLabel.text = strings.someString

Is it possible to store a reference to the containing enum, such that I will not have to reference the full path every time I use a given string? I would love to know if there are any alternative ways of going about this as well.

Upvotes: 0

Views: 228

Answers (3)

Tyler Hillsman
Tyler Hillsman

Reputation: 56

Joakim's answer looks like it answers your question, but another option (with potentially lower memory use?) would be using a typealias.

typealias SubFeatureStrings = Strings.Feature.Subfeature

and then

SubFeatureStrings.someString

The typealias could be nested inside the class/struct where you're calling it, to avoid conflicts across your app.

Upvotes: 4

Gustavo Vollbrecht
Gustavo Vollbrecht

Reputation: 3256

An enum can be enum <#name#> : String

enum Foo : String {
    case bar = "bar"
}

usage: <#something#>.text = Foo.bar.rawValue


For chained purposes

enum SomeEnum {
    enum Foo : String {
        case bar = "bar"
    }
}

usage: <#something#>.text = SomeEnum.Foo.bar.rawValue


Then you can typealias the chain:

typealias foo = SomeEnum.Foo
<#something#>.text = foo.bar.rawValue

Upvotes: 0

numadu78
numadu78

Reputation: 11

enum Strings {
    enum Feature {
        enum Subfeature {
            static var someString: String { "some string".localizedLowerCase }
            static var otherString: String { "some other string".localizedLowerCase }
        }
    }
}

var strings = Strings.Feature.Subfeature.self
someLabel.text = strings.someString
someLabel.text = strings.someOtherString

Upvotes: 1

Related Questions