本文介绍了枚举数据迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用类似java的枚举,您可以在其中拥有带有自定义数据的枚举实例。例如:
I would like to use java-like enums, where you can have enum instances with custom data. For instance:
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;似乎我可以指示变量,而不是值,我只能分配值当使用枚举时,不声明。这将是最好的模拟这种行为的方式?
It seems that I can indicate the variables, but not the values, and I can only assign the values when using the enum, not declaring. Which would be the best way to mimic this behaviour?
推荐答案你可以做这样的事情,这可能是有帮助的: >(这是非常通用的例子)
you can do something like this, which may be helpful: (that is a very generic example only)
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() } } }
那么你可以访问这样的细节:
then you can access to the details like this:
let country: Country = Country.Botwana获取资本
这样:
get the capital
that way:
let capital: String = country.capital()或另一个:
let capital: String = country.all().capital或第三个:
let capital: String = country.capitolName获取标志的颜色:
get the flag's colours:
that way:
let flagColours: Array<UIColor> = country.flagColours()或另一个:
let flagColours: Array<UIColor> = country.all().flagColours或第三个:
let flagColours: Array<UIColor> = country.flagColoursArray更多推荐
枚举数据迅速
发布评论