2015年8月6日 星期四

[Swift] Illiterate Enum members

Sometimes it is useful to illiterate over all members of a enum. Here's hows its done in Swift:

Add a static constant array containing the enum members

1
2
3
4
5
6
7
8
9
    enum Brands: String {
        case Toyota = "Toyota"
        case BMW= "BMW"
        case Tesla = "Tesla"
        case Honda = "Honda"
        case Lexus = "Lexus"
        
        static let allBrands = [Toyota, BMW, Tesla, Honda, Lexus]
    }

To access the data, just illiterate using a for loop:

1
2
3
        for brandNames in Brands.contents {
            println("brandNames.rawValue")
        }

Simple and effective.

沒有留言:

張貼留言