[英]How to make an array string from enum member raw value in swift
我是编程新手,很快。 我有一个像这样的枚举
enum City : String {
case tokyo = "tokyo"
case london = "london"
case newYork = "new york"
}
我能否从枚举原始值中将该城市名称转换为数组? 我希望我能得到这样的东西:
let city = ["tokyo","london","new york"]
这样的事情。
let cities = [City.tokyo, .london, .newYork]
let names = cities.map { $0.rawValue }
print(names) // ["tokyo", "london", "new york"]
要获得所有枚举值作为数组, 请参见this 。
迅捷4.0
如果要遍历枚举,可以这样做。
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
希望这会有所帮助。 请查看此https://stackoverflow.com/a/28341290/2741603了解更多详细信息
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)
以Rintaro的答案为灵感,我创建了两个可在简单枚举中使用的协议。 一种提取所有个案,另一种提取所有rawValue:
protocol Enumeratable: Hashable {
static var cases: [Self] { get }
}
extension Enumeratable {
static var cases: [Self] {
var cases: [Self] = []
var index = 0
for element: Self in AnyIterator({
let item = withUnsafeBytes(of: &index) { $0.load(as: Self.self) }
guard item.hashValue == index else { return nil }
index += 1
return item
}) {
cases.append(element)
}
return cases
}
}
protocol RawValued: Hashable, RawRepresentable {
static var rawValues: [RawValue] { get }
}
extension RawValued {
static var rawValues: [RawValue] {
var rawValues: [RawValue] = []
var index = 0
for element: Self in AnyIterator({
let item = withUnsafeBytes(of: &index) { $0.load(as: Self.self) }
guard item.hashValue == index else { return nil }
index += 1
return item
}) {
rawValues.append(element.rawValue)
}
return rawValues
}
}
游乐场测试:
enum City: String, RawValued, Enumeratable {
case tokyo, london, newYork = "new york"
}
City.cases // [tokyo, london, newYork]
City.rawValues // ["tokyo", "london", "new york"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.