如何在swift中从枚举成员原始值创建数组字符串

时间:2018-01-17 04:27:16

标签: ios swift

我是编程和快速的新手。我有这样的枚举

enum City : String {
    case tokyo = "tokyo"
    case london = "london"
    case newYork = "new york"
}

我可以从enum原始值获取该城市名称吗?我希望我能得到这样的东西:

let city = ["tokyo","london","new york"]

4 个答案:

答案 0 :(得分:3)

像这样。

let cities = [City.tokyo, .london, .newYork]
let names = cities.map { $0.rawValue }
print(names) // ["tokyo", "london", "new york"]

将所有枚举值作为数组see this获取。

答案 1 :(得分:2)

Swift 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

答案 2 :(得分:0)

希望这可能会有所帮助。请查看此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)

答案 3 :(得分:0)

使用Rintaro answer作为灵感我创建了两个在简单枚举中使用的协议。一个用于提取所有案例,另一个用于提取所有rawValues:

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