如果我有以下枚举:
enum FruitTuple
{
static let Apple = (shape:"round",colour:"red")
static let Orange = (shape:"round",colour:"orange")
static let Banana = (shape:"long",colour:"yellow")
}
然后我有以下功能:
static func PrintFruit(fruit:FruitTuple)
{
let shape:String = fruit.shape
let colour:String = fruit.colour
print("Fruit is \(shape) and \(colour)")
}
在fruit.shape
和fruit.colour
我收到错误:
Value of type 'FruitTuple' has no member 'shape'
足够公平,所以我改变了enum的类型:
enum FruitTuple:(shape:String, colour:String)
{
static let Apple = (shape:"round",colour:"red")
static let Orange = (shape:"round",colour:"orange")
static let Banana = (shape:"long",colour:"yellow")
}
但是在枚举声明中我得到了错误:
Inheritance from non-named type '(shape: String, colour: String)'
所以,问题是:是否有可能在枚举中有一个元组并且能够以这种方式引用它的组成部分?我只是缺少一些基本的东西吗?
答案 0 :(得分:5)
正如@MartinR指出的那样。此外,根据Apple文档,"枚举案例可以指定要存储的任何类型的关联值以及每个不同的案例值"。如果您想继续使用static func PrintFruit(fruit:FruitTuple.Apple)
{
let shape:String = fruit.shape
let colour:String = fruit.colour
print("Fruit is \(shape) and \(colour)")
}
,则可能需要执行以下操作:
typealias
我不确定你想要什么,但我想使用typealias FruitTuple = (shape: String, colour: String)
enum Fruit
{
static let apple = FruitTuple("round" , "red")
static let orange = FruitTuple("round", "orange")
static let banana = FruitTuple("long", "yellow")
}
func printFruit(fruitTuple: FruitTuple)
{
let shape:String = fruitTuple.shape
let colour:String = fruitTuple.colour
}
可以帮助你实现目标。
DTOptionsBuilder