2

I am new in programming and swift. I have an enum like this

enum City : String {
    case tokyo = "tokyo"
    case london = "london"
    case newYork = "new york"
}

Could I possibly get that city name to an array from enum raw value? I hope I can get something like this :

let city = ["tokyo","london","new york"]
Jay Patel
  • 2,642
  • 2
  • 18
  • 40
maximiliano
  • 353
  • 5
  • 15
  • This will probably be [addressed soon.](https://github.com/apple/swift-evolution/blob/master/proposals/0194-derived-collection-of-enum-cases.md) – Alexander Jan 17 '18 at 04:40
  • Related: [How to enumerate an enum with String type?](https://stackoverflow.com/questions/24007461/how-to-enumerate-an-enum-with-string-type). – Martin R Jan 17 '18 at 05:47
  • https://stackoverflow.com/questions/32952248/get-all-enum-values-as-an-array/46420714#46420714 City.cases().map { $0.rawValue() } – Nikolay Khramchenko Jul 19 '18 at 10:17

4 Answers4

8

Something like this.

let cities = [City.tokyo, .london, .newYork]
let names = cities.map { $0.rawValue }
print(names) // ["tokyo", "london", "new york"]

To get all enum values as an array see this.

Bilal
  • 18,478
  • 8
  • 57
  • 72
  • Thank you very much. But Can i use for in looping in enum ? Because i have a lot of cities list actually ? – maximiliano Jan 17 '18 at 04:37
  • You have to create an array with all the enum values. Other alternative is to have all the cities in a `plist` in your bundle and use `PropertyListDecoder` with `Codable`. https://useyourloaf.com/blog/using-swift-codable-with-property-lists/ – Bilal Jan 17 '18 at 04:49
4

Swift 4.0

If you want to iterate through enum you can do like this.

enum City : String {

    case tokyo = "tokyo"
    case london = "london"
    case newYork = "new york"

    static let allValues = [tokyo,london,newYork] 
}

let values = City.allValues.map { $0.rawValue }
print(values) //tokyo london new york
Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
1

Hope this might help. Please look into this https://stackoverflow.com/a/28341290/2741603 for more detail

enum City : String {
    case tokyo = "tokyo"
    case london = "london"
    case newYork = "new york"
}

func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
    var k = 0
    return AnyIterator {
        let next = withUnsafeBytes(of: &k) { $0.load(as: T.self) }
        if next.hashValue != k { return nil }
        k += 1
        return next
    }
}


var cityList:[String] = []
for item in iterateEnum(City.self){
    cityList.append(item.rawValue)

}
print(cityList)
adarshaU
  • 950
  • 1
  • 13
  • 31
1

Starting from the answer by https://stackoverflow.com/users/5991255/jaydeep-vora, you can also add conformity to CaseIterable protocol and then use the allCases method

enum City : String, CaseIterable {
    case tokyo = "tokyo"
    case london = "london"
    case newYork = "new york"
}

let values = City.allCases.map { $0.rawValue }
print(values)