Enums 使用swift中的数据枚举

Enums 使用swift中的数据枚举,enums,swift,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]); } 我可以稍后写: Coun

我想使用类似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]);
}
我可以稍后写:

Country.Moldova.capital;

似乎我可以指示变量,但不能指示值,并且我只能在使用枚举时分配值,而不能声明。模仿这种行为的最佳方式是什么?

不幸的是,具有的枚举似乎仅限于文字值。你可能想

作为替代方案,您可以这样做:

let Country = (
    Moldova: (capital: "Chișinău", flagColors: [Color.Blue, Color.Yellow, Color.Red]),
    Botswana: (capital: "Gaborone", flagColors: [Color.Blue, Color.White, Color.Black])
)
let country: Country = Country.Botwana
或者这个:

struct Country {
    let capital: String
    let flagColors: [Color]
}

let Countries = (
    Moldova: Country(capital: "Chișinău", flagColors: [.Blue, .Yellow, .Red]),
    Botswana: Country(capital: "Gaborone", flagColors: [.Blue, .White, .Black])
)

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

获得资本 这样:

let capital: String = country.capital()
let flagColours: Array<UIColor> = country.flagColours()
或其他:

let capital: String = country.all().capital
let flagColours: Array<UIColor> = country.all().flagColours
或者第三个:

let capital: String = country.capitolName
let flagColours: Array<UIColor> = country.flagColoursArray
获取国旗的颜色: 这样:

let capital: String = country.capital()
let flagColours: Array<UIColor> = country.flagColours()
let flagcolors:Array=country.flagcolors()
或其他:

let capital: String = country.all().capital
let flagColours: Array<UIColor> = country.all().flagColours
让flagcolors:Array=country.all().flagcolors
或者第三个:

let capital: String = country.capitolName
let flagColours: Array<UIColor> = country.flagColoursArray
让flagcolors:Array=country.flagcolorsarray

这里是另一个与holex发布的示例类似的通用示例,但更接近Java中的外观。(我喜欢它,因为所有自定义数据都在一个地方)。我没有在单独的方法中打开“self”,而是简单地创建一个静态字典,将每个案例映射到包含适当数据的元组。然后,我可以方便地获取数据

enum TestEnum {
    case One
    case Two
    case Three

    private static let associatedValues = [
        One:    (int: 1, double: 1.0, string: "One"),
        Two:    (int: 2, double: 2.0, string: "Two"),
        Three:  (int: 3, double: 3.0, string: "Three")
    ]

    var int: Int {
        return TestEnum.associatedValues[self]!.int;
    }

    var double: Double {
        return TestEnum.associatedValues[self]!.double;
    }

    var string: String {
        return TestEnum.associatedValues[self]!.string;
    }
}
您可以访问自定义数据,如下所示:

println(TestEnum.One.int)      // 1
println(TestEnum.Two.double)   // 2.0
println(TestEnum.Three.string) // Three

这就是我最后所做的,虽然我不认为这是理想的,但它确实模拟了我所寻找的行为。我非常喜欢这个解决方案,因为它将每个枚举数据保持在一行中。你知道如何让编译器检查所有的案例都包含在
关联值中了吗?