kkris1983
kkris1983

Reputation: 493

Enum with associated value of default type

is there a way to define enum associated value type set as default for all its cases instead of defining it for every each of them like below ?

enum Device {
    case phone(String)
    case watch(String)
    case tablet(String)
}

I want to avoid repeating myself with (String)

Upvotes: 1

Views: 1165

Answers (2)

Paul B
Paul B

Reputation: 5115

If you're happy with literals, then why not use rawValues instead of associated ones:

enum DeviceType: String {
    case phone = "iPhone X"
    case watch = "Longines"
    case tablet = "Samsung"
    // Only literals can serve as raw values, so next line won't work:
    // case notebook = NSLocalizedString("Any personal computer", comment: "")
}

If you need mutable associated values of the same type, you might find Dictionaries useful.

// Add CaseIterable conformance protocol to obtain DeviceType.allCases
enum DeviceType: String, CaseIterable {
    case phone = "iPhone X"
    case watch = "Longines watch"
    case tablet = "Samsung tablet"
    // Only literals can serve as raw values, so next line won't work:
    // case notebook = NSLocalizedString("Any personal computer", comment: "")

    // if you don't want any other vars involved you can add a method to enum
    func localizedName() -> String {
        return NSLocalizedString(self.rawValue, comment: "")
    }
}    
// Create your perfect dict for enum (You'll have to manually add strings to translation)
let deviceTypeLocalized = Dictionary(uniqueKeysWithValues: zip(DeviceType.allCases, DeviceType.allCases.map{ NSLocalizedString($0.rawValue, comment: "") }))
// use (or even change) "associated" values with the power of dicts
let localizedWatchName = deviceTypeLocalized[.watch]
// this is how you get your "associated" value from enum without any external dictionaries, without looking it up.
let localizedTabletName = DeviceType.tablet.localizedName()

Upvotes: 1

simonWasHere
simonWasHere

Reputation: 1340

In this situation it might be easier to define it like this:

enum DeviceType {
    case phone
    case watch
    case tablet
}

struct Device {
    var type: DeviceType
    var name: String
    ... init, etc.
}

Then you can handle the type and string independently of each other, because if every single enum case has a string it sounds like maybe the string is not directly related to the enum value.

Upvotes: 3

Related Questions