Agung
Agung

Reputation: 13803

How to make an array string from enum member raw value in 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"]

Upvotes: 2

Views: 6109

Answers (4)

Nicola Garone
Nicola Garone

Reputation: 11

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) 

Upvotes: 1

adarshaU
adarshaU

Reputation: 960

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)

Upvotes: 1

Jaydeep Vora
Jaydeep Vora

Reputation: 6213

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

Upvotes: 4

Bilal
Bilal

Reputation: 19156

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.

Upvotes: 8

Related Questions