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] {
...
}
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)
As has been said, you can't have multiple rawValues for each enum case, and you also can't have an Array of values as the rawValue
How to proceed depends a lot on how the code is being used. If your intention is to go from String
to your enum
you can facilitate this with a custom initialiser
enum DollarCountries {
case usa, australia, canada
}
extension DollarCountries {
init?(_ rawValue: String) {
switch rawValue {
case "USA", "Palau", "Panama":
self = .usa
case "Australia", "Kiribati", "Nauru":
self = .australia
case "Canada":
self = .canada
default:
return nil
}
}
}
let a = DollarCountries("USA") // .usa
let b = DollarCountries("Kiribati") // .australia
let c = DollarCountries("UK") // nil
if you mainly want to go the other way round, a computed property is all you need:
extension DollarCountries {
var nations: [String] {
switch self {
case .usa:
return ["USA", "Palau", "Panama"]
case .australia:
return ["Australia", "Kiribati", "Nauru"]
case .canada:
return ["Canada"]
}
}
}
If you need both, I'll leave it to you to find a way to implement this without duplicating the arrays
PS: For the nations
computed property, I highly recommend you use Set
if the ordering is not important
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.