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"]
3

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. But Can i use for in looping in enum ? Because i have a lot of cities list actually ?
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. useyourloaf.com/blog/using-swift-codable-with-property-lists
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

Comments

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)

Comments

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) 

1 Comment

Correct answer from Swift 5 as we can use .allCases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.