Search code examples
swiftenumsassociated-types

Is it possible to assign multiple values in an enumeration? Swift language


I did something like this:

enum DollarCountries: String { 
    case usa = "USA", //Countries Where the U.S. Dollar
    case australia = "Australia" //Countries Where the Australian Dollar        
    case canada = "Canada" //Countries Where the Canadian Dollar
}

And I need to make it like that:

enum DollarCountries: String { 
    case usa = "USA", "Palau", "Panama"
    case australia = "Australia", "Kiribati", "Nauru"
    case canada = "Canada"
}

I tried to do this, but it didn't work :c

enum DollarCountries: [String] {
...
}

Solution

  • No , enum can't have multiple raw values.But , you can use competed property like that

    enum DollarCountries1{
        case usa(String?)
        var storedDollar : [String]  {
            ["USA","Australia","Canada"]
        }
    
        var moneyType : String{
            switch self {
            case .usa(let str):
                if storedDollar.contains(str!){
                    return "Dollar";
                }
                return "none"
            default:
                return "none"
            }
         }
    
    }
    
    let country = "USA"
    var forUsa = DollarCountries1.usa(country)
    print(forUsa.moneyType)