Create an enum with parameter

I have some Outputs in my code so I regrouped all that with an Enum String.

The problem is that I have some Outputs containing variable.

Is It possible to create an Enum who takes variable ?

Exemple with this string

print("The name of the Team is \(team.name)")

I wanted to do something like that:

enum Exemple: String {
    case TEAM_NAME(name: String) = "The name of the Team is \(name)"}

print(Exemple.TEAM.NAME("Team 1").rawvalue)

Thank you

3 answers

  • answered 2018-09-21 15:03 Azzaknight

    It is not possible for Enum to have both raw value and associated value. I think you can get by with the associated value. Without the raw value the enum still can provide you enough information to compose the message

  • answered 2018-09-21 15:05 AlexSmet

    You can define an instance method or computed property for enum that will return a string value in depend of enumeration case and associated value. See example for playground.

    enum Example {
        case firstItem
        case secondItem(withText: String)
    
        var stringValue: String {
            switch self {
            case .firstItem: return "Simple string"
            case .secondItem(withText: let text): return "String with additional text: \(text)"
            }
        }
    }
    
    let myEnumItem: Example = .secondItem(withText: "Test")
    let text = myEnumItem.stringValue
    

  • answered 2018-09-21 15:07 inokey

    It's possible to have an enum with associated values for cases. But in order to get the output you're looking for you will need a function.

    enum Example {
    
        case teamName(name: String)
        case teamId(id: Int)
    
        func printName() {
            switch self {
            case .teamName(name: let name):
                print(name)
            default:
                 break
            }
        }
    }
    
    let team = Example.teamName(name: "team1")
    team.printName() // prints team1