枚举数据快速

And*_*lli 7 enums swift

我想使用类似java的枚举,你可以在其中使用自定义数据的枚举实例.例如:

enum Country {
    case Moldova(capital: "Chi?in?u", flagColors: [Color.Blue, Color.Yellow, Color.Red]);
    case Botswana(capital: "Gaborone", flagColors: [Color.Blue, Color.White, Color.Black]);
}
Run Code Online (Sandbox Code Playgroud)

我后来写道:

Country.Moldova.capital;
Run Code Online (Sandbox Code Playgroud)

似乎我可以指示变量,但不能指示值,我只能在使用枚举时指定值,而不是声明.哪种模仿这种行为最好?

hol*_*lex 11

你可以做这样的事情,这可能会有所帮助:( 这只是一个非常通用的例子)

enum Country : Int {
    case Moldova, Botwana;

    //

    func capital() -> String {
        switch (self) {
        case .Moldova:
            return "Chi?in?u"
        case .Botwana:
            return "Gaborone"
        default:
            return ""
        }
    }

    //

    func flagColours() -> Array<UIColor> {
        switch (self) {
        case .Moldova:
            return [UIColor.blueColor(), UIColor.yellowColor(), UIColor.redColor()]
        case .Botwana:
            return [UIColor.blueColor(), UIColor.whiteColor(), UIColor.blackColor()]
        default:
            return []
        }
    }

    //

    func all() -> (capital: String, flagColours: Array<UIColor>) {
        return (capital(), flagColours())
    }

    //

    var capitolName: String {
    get {
        return capital()
    }
    }

    //

    var flagColoursArray: Array<UIColor> {
    get {
        return flagColours()
    }
    }

}
Run Code Online (Sandbox Code Playgroud)

然后你可以访问这样的细节:

let country: Country = Country.Botwana
Run Code Online (Sandbox Code Playgroud)

得到资本

那样:

let capital: String = country.capital()
Run Code Online (Sandbox Code Playgroud)

或其他:

let capital: String = country.all().capital
Run Code Online (Sandbox Code Playgroud)

或第三个:

let capital: String = country.capitolName
Run Code Online (Sandbox Code Playgroud)

得到国旗的颜色:

那样:

let flagColours: Array<UIColor> = country.flagColours()
Run Code Online (Sandbox Code Playgroud)

或其他:

let flagColours: Array<UIColor> = country.all().flagColours
Run Code Online (Sandbox Code Playgroud)

或第三个:

let flagColours: Array<UIColor> = country.flagColoursArray
Run Code Online (Sandbox Code Playgroud)