Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an array string from enum member raw value in swift

Tags:

ios

swift

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"]
like image 576
Agung Laksana Avatar asked Dec 02 '25 09:12

Agung Laksana


2 Answers

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.

like image 187
Bilal Avatar answered Dec 05 '25 02:12

Bilal


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
like image 43
Jaydeep Vora Avatar answered Dec 05 '25 02:12

Jaydeep Vora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!