Reputation: 13803
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
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
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
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