是否可以使用Swift将元组放入枚举中?

Wex*_*Wex 3 enums tuples swift

如果我有以下枚举:

enum FruitTuple
{
    static let Apple = (shape:"round",colour:"red")
    static let Orange = (shape:"round",colour:"orange")
    static let Banana = (shape:"long",colour:"yellow")
}
Run Code Online (Sandbox Code Playgroud)

然后我有以下功能:

static func PrintFruit(fruit:FruitTuple)
{
    let shape:String = fruit.shape
    let colour:String = fruit.colour

    print("Fruit is \(shape) and \(colour)")
}
Run Code Online (Sandbox Code Playgroud)

fruit.shapefruit.colour我得到错误:

Value of type 'FruitTuple' has no member 'shape'

很公平,所以我改变枚举有一个类型:

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")
}
Run Code Online (Sandbox Code Playgroud)

但是在枚举声明中我得到了错误:

Inheritance from non-named type '(shape: String, colour: String)'

所以,问题是:是否有可能在枚举中有一个元组并且能够以这种方式引用它的组成部分?我只是错过了一些基本的东西吗?

Law*_*iet 5

正如@MartinR所指出的那样.此外,根据Apple文档,"枚举案例可以指定要与每个不同案例值一起存储的任何类型的关联值".如果您想继续使用enum,您可能需要执行以下操作:

static func PrintFruit(fruit:FruitTuple.Apple)
{
    let shape:String = fruit.shape
    let colour:String = fruit.colour

    print("Fruit is \(shape) and \(colour)")
}
Run Code Online (Sandbox Code Playgroud)

我不确定你想要什么,但我想使用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
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,你不能将它们用作Dictionary键,因为元组不能符合Hashable(或者任何协议).此外,`Fruit`可以是任何(`String`,`String`),元组.我的`typealias Person =(firstName:String,lastName:String)`tuple是相同的类型.我可以说:'让p:Person = FruitTuple("round","red")`.虽然我想有些人是红色的,圆润的和果味的,但我不认为这是有意的. (2认同)